Find the Level of Tree with Minimum Sum - Problem

Given the root of a binary tree where each node has a value, return the level of the tree that has the minimum sum of values among all the levels.

In case of a tie, return the lowest level. Note that the root of the tree is at level 1 and the level of any other node is its distance from the root + 1.

Input & Output

Example 1 — Basic Case
$ Input: root = [1,7,0,7,-8,null,null]
Output: 3
💡 Note: Level 1: sum = 1, Level 2: sum = 7+0 = 7, Level 3: sum = 7+(-8) = -1. Level 3 has the minimum sum of -1.
Example 2 — Single Node
$ Input: root = [5]
Output: 1
💡 Note: Only one level with sum = 5, so return level 1.
Example 3 — Tie Case
$ Input: root = [1,2,3,4,5,6,7]
Output: 1
💡 Note: Level 1: sum = 1, Level 2: sum = 2+3 = 5, Level 3: sum = 4+5+6+7 = 22. Level 1 has minimum sum.

Constraints

  • The number of nodes in the tree is in the range [1, 104]
  • -105 ≤ Node.val ≤ 105

Visualization

Tap to expand
Find the Level of Tree with Minimum Sum INPUT Binary Tree Structure 1 Level 1 7 0 Level 2 7 -8 Level 3 Input Array: [1, 7, 0, 7, -8, null, null] Green = Min Sum Level ALGORITHM (BFS) 1 Initialize Queue Start BFS with root node 2 Process Each Level Sum all node values per level 3 Track Minimum Sum Update min sum and level 4 Return Result Level Level with minimum sum Level Sums Calculation Level Nodes Sum 1 [1] 1 2 [7, 0] 7 3 [7, -8] -1 Min Sum = -1 at Level 3 FINAL RESULT Minimum Sum Level Highlighted 1 7 0 7 -8 MIN Output: 3 OK - Level 3 has minimum sum = -1 (7 + (-8) = -1) Key Insight: BFS naturally processes nodes level by level, making it ideal for computing level sums. Negative values can make deeper levels have smaller sums than upper levels. Track minimum as you go! TutorialsPoint - Find the Level of Tree with Minimum Sum | BFS Approach
Asked in
Amazon 25 Microsoft 18
28.0K Views
Medium Frequency
~15 min Avg. Time
850 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