Maximum Level Sum of a Binary Tree

Medium BFS

Problem

Given the root of a binary tree, return the level (1-indexed) with the maximum sum of node values. If multiple levels have the same maximum sum, return the smallest level number.

  • The number of nodes in the tree is in the range [1, 10⁴]
  • −10⁵ ≤ Node.val ≤ 10⁵

Example

Input: root = [1,7,0,7,-8,null,null]
Output: 2

The tree levels are: Level 1: [1], sum = 1 Level 2: [7, 0], sum = 7 Level 3: [7, -8], sum = -1 The maximum sum is 7 at level 2, so the output is 2. A brute-force approach might traverse the tree multiple times to compute sums per level, which is inefficient. Instead, a BFS traversal processes nodes level-by-level, accumulating sums in a single pass. The critical insight is that BFS naturally partitions nodes by level, enabling simultaneous sum calculation and comparison.

Approach

Straightforward Solution

A naive solution might perform a DFS to collect nodes per level and then compute sums, requiring extra space and multiple passes. Alternatively, BFS with a queue allows processing each level in a single pass, reducing complexity.

Core Observation

A binary tree can be traversed level-by-level using BFS, which naturally groups nodes by their depth. Summing node values at each level and tracking the maximum sum is straightforward with this approach.

Path to Optimal

Recognizing that BFS inherently processes nodes in level order allows summing values as nodes are dequeued per level. By maintaining a running maximum sum and corresponding level, the algorithm efficiently identifies the level with the greatest sum in O(n) time and O(w) space, where w is the maximum width of the tree.

Optimal Approach

Use a queue initialized with the root node. For each level, iterate over all nodes currently in the queue, summing their values and enqueueing their children. After processing each level, update the maximum sum and record the level if the sum exceeds the previous maximum. Return the level with the highest sum after traversal completes.

Time

O(n)

Each node is enqueued and dequeued exactly once during BFS, resulting in linear time proportional to the number of nodes.

Space

O(w)

The queue stores at most the maximum number of nodes at any level (the tree's maximum width), which can be up to O(n) in the worst case but typically less.

Pattern Spotlight

BFS (Level-Order Traversal with Aggregation)

When a problem requires processing or aggregating nodes by their depth in a tree, BFS naturally partitions nodes level-by-level, enabling efficient single-pass computations per level.

Solution

1from collections import deque
2
3class Solution:
4 def maxLevelSum(self, root: Optional[TreeNode]) -> int:
5 queue = deque([root])
6 level = 1
7
8 best_level = 1
9 best_sum = float("-inf")
10
11 while queue:
12 level_sum = 0
13
14 for _ in range(len(queue)):
15 node = queue.popleft()
16 level_sum += node.val
17
18 if node.left:
19 queue.append(node.left)
20
21 if node.right:
22 queue.append(node.right)
23
24 if level_sum > best_sum:
25 best_sum = level_sum
26 best_level = level
27
28 level += 1
29
30 return best_level

Step-by-Step Solution

1

Initialize BFS Queue and Tracking Variables

5queue = deque([root])
6level = 1
8best_level = 1
9best_sum = float("-inf")

Objective

To set up the queue with the root node and initialize variables to track the current level and the best level with maximum sum.

Key Insight

Starting the queue with the root node establishes the BFS frontier. Initializing the level counter at 1 aligns with the problem's 1-indexed level numbering. Setting the best sum to negative infinity ensures any level sum will update it, handling negative values correctly.

Interview Quick-Check

Core Logic

Initializing the queue with the root node sets the stage for level-order traversal.

State & Boundaries

Level numbering starts at 1 to match problem requirements.

Common Pitfalls & Bugs

Setting best_sum to negative infinity handles trees with negative node values correctly.

2

Traverse Tree Level-by-Level and Aggregate Sums

11while queue:
12 level_sum = 0
14 for _ in range(len(queue)):
15 node = queue.popleft()
16 level_sum += node.val
18 if node.left:
19 queue.append(node.left)
21 if node.right:
22 queue.append(node.right)
24 if level_sum > best_sum:
25 best_sum = level_sum
26 best_level = level
28 level += 1

Objective

To process each level's nodes, sum their values, enqueue their children, and update the maximum sum and corresponding level.

Key Insight

The for-loop iterates over all nodes currently in the queue, which represents exactly one level. Summing node values during this iteration captures the total for that level. Enqueuing children prepares the queue for the next level. Updating the best sum and level only when a strictly greater sum is found ensures the smallest level is returned in case of ties.

Interview Quick-Check

Core Logic

Processing all nodes in the queue per iteration corresponds to processing one level of the tree.

State & Boundaries

The loop runs exactly len(queue) times to isolate nodes of the current level.

Common Pitfalls & Bugs

Failing to update the best_level only when a strictly greater sum is found can cause incorrect results when multiple levels share the same sum.

Complexity

Each node is processed once, and children are enqueued once, ensuring O(n) time complexity.

3

Return the Level with the Maximum Sum

30return best_level

Objective

To output the level number that has the maximum sum after completing the BFS traversal.

Key Insight

After processing all levels, the recorded best_level corresponds to the level with the highest sum. Returning this value satisfies the problem's requirement.

Interview Quick-Check

Core Logic

Returning best_level provides the final answer after all levels have been evaluated.

Line Analysis

This solution has 1 Critical line interviewers watch for.

Line 24 Critical
if level_sum > best_sum:

Compare the current level sum to the best sum found so far.

This conditional identifies if the current level has a strictly greater sum, which is necessary to update the best level.

Line 5 Core
queue = deque([root])

Initialize the BFS queue with the root node.

Starting the queue with the root node sets the initial frontier for level-order traversal, ensuring the algorithm begins at the top of the tree.

Line 14 Core
for _ in range(len(queue)):

Iterate over all nodes currently in the queue, representing one level.

Using the current queue length captures exactly the nodes at the current level, isolating level processing.

Line 15 Core
node = queue.popleft()

Remove the next node from the queue for processing.

Dequeuing nodes in FIFO order ensures nodes are processed level-by-level in BFS order.

Line 19 Core
queue.append(node.left)

Add the left child to the queue for future processing.

Enqueuing children extends the BFS frontier to the next level, enabling level-order traversal.

Line 22 Core
queue.append(node.right)

Add the right child to the queue for future processing.

Enqueuing the right child continues the BFS traversal into the next level.

Line 25 Core
best_sum = level_sum

Update the best sum to the current level sum.

Recording the new maximum sum ensures the algorithm tracks the highest level sum encountered.

Line 26 Core
best_level = level

Update the best level to the current level number.

Updating the best level when a new maximum sum is found ensures the smallest level with the maximum sum is recorded.

Line 9 Core
best_sum = float("-inf")

Initialize the variable to track the maximum sum found so far.

Setting best_sum to negative infinity ensures that any level sum, including negative sums, will update this variable correctly.

Line 12 Core
level_sum = 0

Initialize the sum accumulator for the current level.

Resetting level_sum to zero at the start of each level ensures accurate aggregation of node values for that level.

Line 16 Core
level_sum += node.val

Add the current node's value to the level sum.

Accumulating node values during level processing enables calculation of the total sum for that level.

Line 30 Core
return best_level

Return the level with the maximum sum after traversal completes.

Returning best_level provides the final answer as required by the problem.

Line 8 Standard
best_level = 1

Initialize the variable to track the level with the maximum sum.

This variable stores the best level found so far, starting at 1 since the root level is the first to be processed.

Line 11 Standard
while queue:

Begin the BFS loop that continues while there are nodes to process.

The while loop controls the traversal, ensuring all levels are processed until no nodes remain.

Line 18 Standard
if node.left:

Check if the current node has a left child.

Verifying the existence of a left child prevents errors and ensures only valid nodes are enqueued for the next level.

Line 21 Standard
if node.right:

Check if the current node has a right child.

Ensures only valid right children are enqueued, maintaining correctness of traversal.

Line 28 Standard
level += 1

Increment the level counter to move to the next level.

Advancing the level counter maintains accurate tracking of the current depth in the tree.

Line 6 Standard
level = 1

Initialize the current level counter to 1.

Level numbering starts at 1 to align with the problem's requirement that levels are 1-indexed.

Test Your Understanding

Why does BFS guarantee that nodes are processed level-by-level, enabling correct aggregation of sums per level?

Because BFS uses a queue that enqueues all children of nodes at the current level before moving to the next, it processes nodes in order of their depth, ensuring all nodes at one level are processed before any nodes at the next level.

Related Problems

BFS pattern

Don't just read it. Drill it.

Reconstruct Maximum Level Sum of a Binary Tree from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.

Unlock the Maximum Level Sum of a Binary Tree drill

or drill a free problem