InterviewPrepKit

Home / Coding / Trees

Maximum Level Sum of a Binary Tree

medium Original ↗
Solving tips
  • 'Per-level' is BFS's native vocabulary: snapshot len(queue) before draining so one outer-loop iteration sums exactly one level. O(n) time, O(w) space.
  • DFS works too if each call carries its depth and accumulates into sums[depth]; scan for the first max afterward (O(h) space).
  • Pitfall: values can be negative, so never return early when a level sum drops — a later level can rebound; examine all levels.
  • Pitfall: seed best_sum from the root or -inf (not 0), use strict > so ties break toward the shallower level, and remember levels are 1-indexed in the answer.

Problem

Given the root of a binary tree, label the root’s level as 1, its children as level 2, and so on. For each level, compute the sum of all node values on it. Return the smallest level number whose sum is maximal (ties break toward the shallower level). Node values can be negative.

Examples

  • Input: root = [1,7,0,7,-8,null,null] → Output: 2 Level sums: level 1 = 1, level 2 = 7 + 0 = 7, level 3 = 7 + (-8) = -1. The maximum is 7, first reached at level 2.
  • Input: root = [989,null,10250,98693,-89388,null,null,null,-32127] → Output: 2 Sums: 989, 10250, 9305, -32127. Level 2 wins with 10250.
  • Input: root = [-1,-2,-3] → Output: 1 Sums: -1, -5. All negative — the maximum is -1 at level 1.

Constraints

  • 1 <= n <= 10^4 nodes; -10^5 <= Node.val <= 10^5.
  • Values may be negative, so you cannot stop early when a level sum drops.
  • Expected: one O(n) traversal.

Think about it first

Hint 1 What traversal naturally groups nodes level by level?
Hint 2 With breadth-first search, one iteration of the outer loop processes exactly one level — sum the values as you drain the queue's current length.
Hint 3 DFS works too: carry the depth as a parameter and accumulate into `sums[depth]`. Either way, finish all levels, then take the first index of the maximum — don't return early, negatives can rebound.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.