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 of a Binary Tree INPUT Binary Tree Structure 1 Level 1 7 0 Level 2 7 -8 Level 3 root = [1,7,0,7,-8,null,null] Sum L1: 1 | Sum L2: 7 | Sum L3: -1 Max Sum = 7 at Level 2 ALGORITHM (BFS) 1 Initialize Queue Add root to queue maxSum=MIN, level=0 2 Process Each Level While queue not empty: - Get level size 3 Calculate Level Sum Sum all node values Add children to queue 4 Update Maximum If sum > maxSum: Update maxSum, result BFS Processing: L1: [1] --> sum=1 L2: [7,0] --> sum=7 [MAX] L3: [7,-8] --> sum=-1 FINAL RESULT Level with Max Sum 1 7 0 7 -8 Output 2 [OK] Level 2 Sum = 7 + 0 = 7 (Maximum Sum) Smallest level with max Key Insight: BFS naturally processes tree level by level. Track the sum at each level and compare with maximum. Return the smallest level number when sum equals maximum (handles ties by returning first occurrence). TutorialsPoint - Maximum Level Sum of a Binary Tree | BFS Approach
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