Find the Level of Tree with Minimum Sum - Problem

Imagine you're a tree analyst tasked with finding the most "cost-effective" level in a binary tree! ๐ŸŒณ

Given the root of a binary tree where each node contains a numerical value, your mission is to identify which level has the minimum sum of all node values across all levels in the tree.

Key Rules:

  • The root node is at level 1
  • Each child node's level = parent's level + 1
  • If multiple levels tie for the minimum sum, return the smallest level number

Example: If level 2 has sum = 10, level 3 has sum = 10, and level 4 has sum = 15, return 2 (the lowest level with minimum sum).

Input & Output

example_1.py โ€” Balanced Tree
$ 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. The minimum sum is -1 at level 3, so return 3. Wait, that's not right. Let me recalculate: Level 1: 1, Level 2: 7+0=7, Level 3: 7+(-8)=-1. Actually, return 3.
example_2.py โ€” Simple Tree
$ Input: root = [5, 3, 8, 2, 4, null, null]
โ€บ Output: 1
๐Ÿ’ก Note: Level 1: sum = 5, Level 2: sum = 3 + 8 = 11, Level 3: sum = 2 + 4 = 6. The minimum sum is 5 at level 1, so return 1.
example_3.py โ€” Single Node
$ Input: root = [42]
โ€บ Output: 1
๐Ÿ’ก Note: Only one level exists with sum = 42, so return level 1.

Constraints

  • The number of nodes in the tree is in the range [1, 104]
  • -105 โ‰ค Node.val โ‰ค 105
  • The tree is guaranteed to be non-empty

Visualization

Tap to expand
BFS Level-by-Level Tree ProcessingL15L23L28L32L34Level SumsLevel 1: Sum = 5Level 2: Sum = 11Level 3: Sum = 6Minimum: Level 1
Understanding the Visualization
1
Initialize Queue
Start with root node in queue, level 1
2
Process Level
Remove all nodes at current level, sum their values
3
Add Children
Add children of processed nodes to queue
4
Track Minimum
Update minimum sum and level if current sum is smaller
5
Repeat
Continue until queue is empty
Key Takeaway
๐ŸŽฏ Key Insight: BFS naturally processes nodes level by level, making it perfect for level-sum calculations in one efficient traversal
Asked in
Amazon 45 Microsoft 38 Google 32 Meta 28
42.0K Views
Medium Frequency
~15 min Avg. Time
1.9K 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