// 1161. Maximum Level Sum of a Binary Tree
class Solution {
public int maxLevelSum(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
int level = 1;
int ans = 0;
int levelSum;
int maxLevelSum = Integer.MIN_VALUE;
int levelSize;
while (!q.isEmpty()) {
levelSum = 0;
levelSize = q.size();
for (int i = 0; i < levelSize; ++i) {
TreeNode peek = q.poll();
levelSum += peek.val;
if (peek.left != null) {
q.offer(peek.left);
}
if (peek.right != null) {
q.offer(peek.right);
}
}
if (levelSum > maxLevelSum) {
maxLevelSum = levelSum;
ans = level;
}
++level;
}
return ans;
}
}