[LeetCode] Maximum Level Sum of a Binary Tree

1161. Maximum Level Sum of a Binary Tree

Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.

Return the smallest level x such that the sum of all the values of nodes at level x is maximal.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxLevelSum(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
long res = LONG_MIN;
int lvl = 1, curLvl = 1;
while(!q.empty()) {
long sum = 0;
int count = q.size();
while(count--) {
auto node = q.front(); q.pop();

sum += node->val;

if(node->left != nullptr)
q.push(node->left);
if(node->right != nullptr)
q.push(node->right);

}
if(res < sum) {
res = sum;
lvl = curLvl;
}
curLvl++;
}
return lvl;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/25/PS/LeetCode/maximum-level-sum-of-a-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.