Skip to content
Problem 1161 · LeetCode 1161(opens in a new tab)

Maximum Level Sum of a Binary Tree

MediumBreadth-first search

Number the levels of a binary tree, starting from its root: the root is on level 1, its children are on level 2, their children on level 3, and so on.

Add up the values on each level. Return the number of the level with the largest total. If several levels share that largest total, return the smallest of their numbers.

Example 1

Input:  root = [1, 6, -2, 3, -9, null, 4]
Output: 2
Why:    the level totals are 1, 4 and -2
2 more examples and the constraints

Example 2

Input:  root = [3, 1, 2]
Output: 1
Why:    levels 1 and 2 both total 3; the smaller level wins

Example 3

Input:  root = [-5, -1, -2]
Output: 2
Why:    -3 is larger than -5

Constraints

  • The tree has between 1 and 10,000 nodes
  • −100,000 ≤ each node value ≤ 100,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. DFS with a sum per depthO(n)
  2. BFS, one level at a timeO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 nodesVerdict
DFS with a sum per depthO(n)
Passes; deep trees need a big stack
BFS, one level at a timeO(n)
Best; levels come for free

n = number of nodes, h = tree height, w = widest level. Both touch every node once.

Edge cases to test

  • One node. A tree of just [7] has one level, so the answer is 1.
  • Every sum negative. [-5, -1, -2] has totals −5 and −3; the answer is 2, not "no level".
  • A tie. [3, 1, 2] has two levels totalling 3; return 1, the smaller.
  • A long chain. One node per level, so each level’s total is just that node.

Common mistakes

  • Replacing the best on >=, which returns the last tied level instead of the first.
  • Starting the best sum at 0, so a tree with only negative totals returns level 0.
  • Counting levels from 0 and forgetting to add one.

How to talk through it

  1. 1Clarify. Levels count from 1? On a tie, the smallest level? Can values be negative?
  2. 2Name the traversal. A total per level is level-order traversal, so BFS with a queue.
  3. 3Explain the size trick. At the start of each round the queue holds exactly one level; read its size before popping.
  4. 4Code it. Start the best at minus infinity and update only on a strictly larger sum.
  5. 5Test out loud. Run one node, all negative values and a tie between two levels.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?