Skip to content
Decoder

Maximum Level Sum of a Binary Tree

Medium

Problem

The root of a binary tree is on level 1, its children on level 2, and so on. Given the root, add up the values on each level and return the level number whose total is largest. If several levels tie, return the smallest level number.

Trees in the examples are written in level order (top to bottom, left to right), with null for a missing child, the same way the tests build them.

Example 1

Input
[1, 7, 0, 7, -8]
Output
2
Why
level sums: 1, 7, -1

Example 2

Input
[3, 1, 2]
Output
1
Why
3 and 3 tie, so the higher level wins

Constraints

  • 1 <= number of nodes <= 10^4
  • -10^5 <= Node.val <= 10^5

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.