InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Maximum Level Sum of a Binary Tree

medium Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug