Maximum Level Sum of a Binary Tree (LeetCode 1161): Solution and Explanation

Medium
Tree
Depth First Search
Breadth First Search
Binary Tree

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

  1. Put the root in a queue. Set best_sum to minus infinity and best_level to 0.
  2. While the queue is not empty, increase level and start level_sum at 0.
  3. Dequeue exactly as many nodes as the queue held when the level began. Add each value to level_sum and enqueue its children.
  4. If level_sum > best_sum, store the sum and the current level.
  5. Return best_level once the queue is empty.

Step-by-step example

root = [1,7,0,7,-8,null,null]
  1. 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.
  2. Level 2 holds 7 and 0. Dequeuing them gives a sum of 7 and enqueues 7 and -8 from the left child.
  3. 7 > 1, so level 2 becomes the best with best_sum = 7.
  4. Level 3 holds 7 and -8, summing to -1. That is less than 7, so level 2 stays the best.
  5. 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_level
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Every node is enqueued once and dequeued once, and each dequeue does constant work.

Space

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_sum at 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.