Code & Func
2019-12-26

第49天。

今天的题目是Maximum Level Sum of a Binary Tree:

送分题,直接用层次便利计算每一层的元素之和,然后去最大即可。

1
int maxLevelSum(TreeNode* root) {
2
if (!root) return -1;
3
4
int max_level = -1, max_sum = INT_MIN;
5
6
queue<TreeNode *> q;
7
q.push(root);
8
9
int cur_level = 1, cur_sum;
10
11
while(!q.empty()) {
12
cur_sum = 0;
13
for(int i = 0, size = q.size(); i < size; i++) {
14
root = q.front(); q.pop();
15
cur_sum += root->val;
12 collapsed lines
16
if (root->left) q.push(root->left);
17
if (root->right) q.push(root->right);
18
}
19
if (cur_sum > max_sum) {
20
max_sum = cur_sum;
21
max_level = cur_level;
22
}
23
cur_level++;
24
}
25
26
return max_level;
27
}
上一条动态