Maximum Level Sum of a Binary Tree - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
root = [1,7,0,7,-8,null,null]
›
Output:
2
💡 Note:
Level 1: sum = 1. Level 2: sum = 7 + 0 = 7. Level 3: sum = 7 + (-8) = -1. Maximum sum is 7 at level 2.
Example 2 — Single Node
$
Input:
root = [989,null,10250,98693,-89388,null,null,null,-32127]
›
Output:
2
💡 Note:
Level 1: sum = 989. Level 2: sum = 10250. Level 3: sum = 98693 + (-89388) = 9305. Level 4: sum = -32127. Maximum sum is 10250 at level 2.
Example 3 — Negative Values
$
Input:
root = [-100,-200,-300,-20,-5,-10,null]
›
Output:
3
💡 Note:
Level 1: sum = -100. Level 2: sum = -200 + (-300) = -500. Level 3: sum = -20 + (-5) + (-10) = -35. Maximum sum is -35 at level 3.
Constraints
- The number of nodes in the tree is in the range [1, 104]
- -105 ≤ Node.val ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Binary tree with nodes containing integer values
2
Level Sums
Calculate sum for each level of the tree
3
Maximum Level
Return the smallest level number with maximum sum
Key Takeaway
🎯 Key Insight: BFS naturally processes nodes level by level, making it perfect for calculating level sums efficiently
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code