Maximum Level Sum of a Binary Tree

Given the root of a binary tree, the root is on level 1, its children on level 2, and so on. Return the smallest level x such that the sum of all node values on level x is the largest among all levels.

30:00

Maximum Level Sum of a Binary Tree
medium
Free written solution
Topics
Companies

Given the root of a binary tree, the root is on level 1, its children on level 2, and so on. Return the smallest level x such that the sum of all node values on level x is the largest among all levels.

Example 1:
Input: {"root":[1,7,0,7,-8,null,null]}
Output: 2
Constraints:
  • The number of nodes in the tree is in the range [1,104][1, 10^4].

  • −105≤Node.val≤105-10^5 \leq \text{Node.val} \leq 10^5

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[1,7,0,7,-8,null,null]}

No level has been summed yet, so best_sum starts at minus infinity and best_level at 0.

L1L2L31707-8

queue

empty

dequeued node
level being summed
queued for next level
best level
Variables
VariableValue
level0
level_sum-
best_sum-inf
best_level0
DepthFunction Call
Stack empty
0/17