1161. Maximum Level Sum of a Binary Tree 最大层内元素和

@TOC

# 题目描述

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.

Example 1:

``````Input: [1,7,0,7,-8,null,null]
Output: 2
Explanation:
Level 1 sum = 1.
Level 2 sum = 7 + 0 = 7.
Level 3 sum = 7 + -8 = -1.
So we return the level with the maximum sum which is level 2.
``````

Note:

1. The number of nodes in the given tree is between 1 and 10^4.
2. `-10^5 <= node.val <= 10^5`

# 解题方法

# BFS

BFS需要一个队列存放当前层的所有叶子节点，然后出队列并且对这一层的所有叶子节点求和。

C++代码如下：

``````/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxLevelSum(TreeNode* root) {
int res_sum = INT_MIN;
int res_level = 1;
queue<TreeNode*> que;
que.push(root);
int level = 1;
while (!que.empty()) {
int size = que.size();
int level_sum = 0;
while (size --) {
TreeNode* cur = que.front(); que.pop();
if (!cur) continue;
level_sum += cur->val;
que.push(cur->left);
que.push(cur->right);
}
if (level_sum > res_sum) {
res_sum = level_sum;
res_level = level;
}
level ++;
}
return res_level;
}
};
``````

# 日期

2019 年 9 月 27 日 —— 昨天面快手，竟然是纯刷题