Maximum Level Sum of a Binary Tree

Medium

Description

Given the root of a binary tree, return the smallest level number (1-indexed) with the maximum sum of node values. If there are ties, return the smallest level.

Examples

Input:root = [1,7,0,7,-8,null,null]
Output:2
Explanation:

Level 2 sum = 7+0=7.

Input:root = [5,2,3,-1,4,6,7]
Output:3
Explanation:

Level 1 sum = 5. Level 2 sum = 2+3 = 5. Level 3 sum = -1+4+6+7 = 16. Level 3 has the maximum sum of 16.

Input:root = [10,-5,15,null,8,null,20]
Output:1
Explanation:

Level 1 sum = 10. Level 2 sum = -5+15 = 10. Level 3 sum = 8+20 = 28. The maximum level sum is 28 at level 3, so the output is 3.

Constraints

  • 1 ≤ nodes ≤ 10⁴

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!