Maximum Level Sum of a Binary Tree (LeetCode 1161): Solution and Explanation
You get the root of a binary tree. Number the levels from 1 at the root, add up the values on each level, and return the smallest level number whose sum is the largest.
Intuition
The answer depends on one number per level, so the natural tool is a traversal that finishes one level before it starts the next. That is exactly what breadth-first search does.
In a BFS, at the moment a level begins, the queue holds every node of that level and nothing else. Reading the queue length at that moment tells you how many nodes to dequeue and add before the level is over.
Values can be negative, so you cannot assume deeper or wider levels have larger sums. Compare every level's total, and only replace the best on a strictly larger sum so that a tie keeps the earlier, smaller level.
Approach: BFS with a per-level sum
- Put the root in a queue. Set
best_sumto minus infinity andbest_levelto 0. - While the queue is not empty, increase
leveland startlevel_sumat 0. - Dequeue exactly as many nodes as the queue held when the level began. Add each value to
level_sumand enqueue its children. - If
level_sum > best_sum, store the sum and the current level. - Return
best_levelonce the queue is empty.
Step-by-step example
root = [1,7,0,7,-8,null,null]
- Level 1 holds only the root 1, so its sum is 1. It is the first level, so best_level = 1 and best_sum = 1.
- Level 2 holds 7 and 0. Dequeuing them gives a sum of 7 and enqueues 7 and -8 from the left child.
- 7 > 1, so level 2 becomes the best with best_sum = 7.
- Level 3 holds 7 and -8, summing to -1. That is less than 7, so level 2 stays the best.
- The queue is empty. Return 2.
Code: Python, Java, C++
1class Solution:
2 def maxLevelSum(self, root: Optional[TreeNode]) -> int:
3 best_sum = float('-inf')
4 best_level = 0
5 level = 0
6 queue = deque([root])
7 while queue:
8 level += 1
9 level_sum = 0
10 for _ in range(len(queue)):
11 node = queue.popleft()
12 level_sum += node.val
13 if node.left:
14 queue.append(node.left)
15 if node.right:
16 queue.append(node.right)
17 if level_sum > best_sum:
18 best_sum = level_sum
19 best_level = level
20 return best_level1class Solution {
2 public int maxLevelSum(TreeNode root) {
3 int bestSum = Integer.MIN_VALUE;
4 int bestLevel = 0;
5 int level = 0;
6 Queue<TreeNode> queue = new ArrayDeque<>();
7 queue.offer(root);
8 while (!queue.isEmpty()) {
9 level++;
10 int levelSum = 0;
11 for (int i = queue.size(); i > 0; i--) {
12 TreeNode node = queue.poll();
13 levelSum += node.val;
14 if (node.left != null) {
15 queue.offer(node.left);
16 }
17 if (node.right != null) {
18 queue.offer(node.right);
19 }
20 }
21 if (levelSum > bestSum) {
22 bestSum = levelSum;
23 bestLevel = level;
24 }
25 }
26 return bestLevel;
27 }
28}1class Solution {
2public:
3 int maxLevelSum(TreeNode* root) {
4 int bestSum = INT_MIN;
5 int bestLevel = 0;
6 int level = 0;
7 queue<TreeNode*> q;
8 q.push(root);
9 while (!q.empty()) {
10 level++;
11 int levelSum = 0;
12 for (int i = q.size(); i > 0; i--) {
13 TreeNode* node = q.front();
14 q.pop();
15 levelSum += node->val;
16 if (node->left) {
17 q.push(node->left);
18 }
19 if (node->right) {
20 q.push(node->right);
21 }
22 }
23 if (levelSum > bestSum) {
24 bestSum = levelSum;
25 bestLevel = level;
26 }
27 }
28 return bestLevel;
29 }
30};Time and space complexity
O(n)
Every node is enqueued once and dequeued once, and each dequeue does constant work.
O(w)
The queue holds at most two levels at a time, so its size is bounded by the widest level w, which can be about n/2 for a complete tree.
Other approaches
DFS with a sums list (time O(n), space O(h))
Walk the tree depth first while passing the depth. Add each node's value to sums[depth], growing the list when a new depth appears. Then pick the first index with the largest value. It uses O(h) stack space plus one slot per level.
BFS that collects each level as a list (time O(n), space O(n))
Run a standard level order traversal that returns a list of lists, then sum each inner list. It is easy to write from a known template but stores every value a second time.
Common mistakes
- Starting
best_sumat 0. If every level sum is negative, no level ever beats 0 and you return the wrong level. - Using
>=when comparing to the best. A later level with an equal sum would replace the earlier one, but the problem asks for the smallest level. - Reading
len(queue)inside the loop condition while children are being added. Capture the level size before dequeuing so the next level's nodes are not counted in this one. - Returning a 0-indexed level. The root is on level 1.
Frequently asked questions
Why do ties go to the smaller level?
The problem asks for the smallest level with the maximal sum. Scanning levels from the top and replacing the best only on a strictly larger sum keeps the first level that reached it.
Can the answer be a level other than the widest one?
Yes. Node values can be negative, so a wide level full of negative numbers can have a smaller sum than a single positive root.
Is BFS or DFS better here?
Both are O(n) time. BFS finishes one level before the next, so you can compare sums as you go. DFS needs a list of partial sums and a final scan, but its memory depends on height rather than width.
Can the level sum overflow a 32-bit integer?
No. At most 10^4 nodes with absolute values up to 10^5 gives at most 10^9 in absolute value, which fits in a 32-bit signed integer.