Maximum Level Sum of a Binary Tree

Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.

Return the smallest level x such that the sum of all the values of nodes at level x is maximal.

Example 1
        1
       / \
      7   0
     / \
    7  -8
Inputroot = [1,7,0,7,-8,null,null]
Output2
Level 1 sum is 1, level 2 sum is 7, and level 3 sum is -1, so level 2 has the maximum sum.
Example 2
                  989
                     \
                    10250
                   /     \
              98693     -89388
                            \
                          -32127
Inputroot = [989,null,10250,98693,-89388,null,null,null,-32127]
Output2
The level with the maximum sum is level 2.

Constraints

  • The number of nodes in the tree is in the range [1, 10^4].
  • -10^5 <= Node.val <= 10^5

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate