Binary Tree - BFS· 25 min

Maximum Level Sum of a Binary Tree

LeetCode #1161 · Medium · Solution walkthrough with Java and Python code

Binary Tree - BFS · Medium

LeetCode 1161: Maximum Level Sum of a Binary Tree — solution

Solve LeetCode 1161 with a level-order BFS that sums each level and keeps the first level with the largest sum — O(n) time, O(w) space.

Problem in plain words

Number the levels of a binary tree starting from 1 at the root. Add up the values on each level. Return the number of the level with the biggest total; if several levels tie, return the smallest such level number.

Example: root 2, children -5 and 9, and 9 has a child 1. The level sums are 2, 4 and 1, so the answer is level 2.

Intuition

We need an aggregate per level, which is exactly what a level-order traversal gives us. Process the BFS queue one level at a time, compute that level's sum, and compare it with the best seen so far. Updating only on a strictly larger sum automatically keeps the earliest level on ties.

Approach

  1. Start a queue with the root, level = 0, bestSum = -infinity, bestLevel = 1.
  2. While the queue is non-empty, increment level and pop exactly the current queue size worth of nodes, adding their values to sum and enqueuing their children.
  3. If sum > bestSum, record bestSum = sum and bestLevel = level.
  4. Return bestLevel.

Dry run

LevelNodesSumBest (sum, level)
122(2, 1)
2-5, 94(4, 2)
311(4, 2)

Java solution

java
class Solution {
    public int maxLevelSum(TreeNode root) {
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        long bestSum = Long.MIN_VALUE;
        int bestLevel = 1;
        int level = 0;
        while (!queue.isEmpty()) {
            level++;
            long sum = 0;
            for (int i = queue.size(); i > 0; i--) {
                TreeNode node = queue.poll();
                sum += node.val;
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            if (sum > bestSum) {
                bestSum = sum;
                bestLevel = level;
            }
        }
        return bestLevel;
    }
}

Python solution

python
class Solution:
    def maxLevelSum(self, root: Optional[TreeNode]) -> int:
        best_sum, best_level, level = float('-inf'), 1, 0
        queue = deque([root])
        while queue:
            level += 1
            total = 0
            for _ in range(len(queue)):
                node = queue.popleft()
                total += node.val
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            if total > best_sum:
                best_sum, best_level = total, level
        return best_level

Complexity

MeasureCostWhy
TimeO(n)Each node is enqueued and dequeued once.
SpaceO(w)The queue holds at most one level of nodes.

Edge cases and common mistakes

  • All-negative trees — initialise the best sum to negative infinity (or the root level's sum), never to 0, or you may return a level that does not exist.
  • Using `>=` — that would return the last level among ties. The problem wants the smallest level, so update only on a strictly larger sum.
  • Off-by-one level numbers — levels start at 1, not 0.
  • Overflow worries — a level's sum fits in int for the given limits, but using long costs nothing and is safer.
›Can DFS solve this?

Yes. Pass the depth through a DFS and add each node's value to sums[depth] in a growing list. Afterwards scan the list for the first maximum. Same O(n) time; space becomes O(h + number of levels).