Skip to content

Commit a446174

Browse files
Create max_level_sum_binary_tree.cpp
1 parent 8d9c1fe commit a446174

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

max_level_sum_binary_tree.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
int maxLevelSum(TreeNode* root) {
15+
if(!root) return 0;
16+
17+
int max_ = INT_MIN;
18+
int maxLevel = 0, level = 0;
19+
queue<TreeNode*> q;
20+
q.push(root);
21+
22+
while(!q.empty()) {
23+
int n = q.size();
24+
int sum_ = 0;
25+
level++;
26+
while(n--) {
27+
auto current = q.front();
28+
q.pop();
29+
sum_ += current->val;
30+
if(current->left)
31+
q.push(current->left);
32+
if(current->right)
33+
q.push(current->right);
34+
}
35+
if(sum_ > max_){
36+
max_ = sum_;
37+
maxLevel = level;
38+
}
39+
}
40+
return maxLevel;
41+
}
42+
};

0 commit comments

Comments
 (0)