代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxLevelSum(TreeNode root) {
if(root==null)return 0;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
int max = root.val;
int layer = 0;
int res = 1;
while(!q.isEmpty()){
layer++;
int size = q.size();
int curSum = 0;
for(int i=0;i<size;i++){
TreeNode curNode = q.poll();
curSum += curNode.val;
if(curNode.left!=null)q.offer(curNode.left);
if(curNode.right!=null)q.offer(curNode.right);
}
if(curSum>max){
max = curSum;
res = layer;
}
}
return res;
}
}