LeetCode 1161. Maximum Level Sum of a Binary Tree
suppose the level of root is 1.
now we need to return the smallest level x that sum of all that node values of that level is the max.
of course we can do that using level order traverse and maintain the smallest level and return it. but it not sounds like alright.
however, i still implemented it.
class Solution {
public int maxLevelSum(TreeNode root) {
if (root == null) return -1;
Queue<TreeNode> queue = new LinkedList<>();
TreeNode cur = root;
queue.offer(cur);
//int sum = 0;
int maxSum = Integer.MIN_VALUE;
int levelCounter = 0;
int minLevel = Integer.MAX_VALUE;
while (!queue.isEmpty()) {
levelCounter++;
int size = queue.size();
int sum = 0;
for (int i = 0; i < size; i++) {
cur = queue.poll();
sum += cur.val;
if (cur.left != null) queue.offer(cur.left);
if (cur.right != null) queue.offer(cur.right);
}
System.out.println(sum);
if (sum > maxSum) {
minLevel = levelCounter;
maxSum = sum;
}
}
return minLevel;
}
}

浙公网安备 33010602011771号