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
Maximum Level Sum: Find Level with Highest Sum1Level 1: Sum = 170Level 2: Sum = 7 + 0 = 7 (Maximum!)7-8Level 3: Sum = 7 + (-8) = -1Result Found!Maximum Sum: 7At Level: 2Answer: 2Algorithm: Use BFS to process each level, calculate sums, return level with maximum sumLevel 1: 1 | Level 2: 7 (MAX) | Level 3: -1
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
Asked in
Facebook 25 Amazon 20 Microsoft 15 Google 12
28.5K Views
Medium Frequency
~15 min Avg. Time
945 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen