Maximum Level Sum of a Binary Tree - Problem
Maximum Level Sum of a Binary Tree

Imagine you're exploring a multi-story building where each floor represents a level in a binary tree. Your task is to find which floor has the maximum sum of all room numbers on that floor!

Given the root of a binary tree, where the root is at level 1, its children are at level 2, and so on, you need to:

๐ŸŽฏ Calculate the sum of all node values at each level
๐Ÿ” Find the level with the maximum sum
๐Ÿ“ Return the smallest level number if there's a tie

For example, if level 2 has sum 15 and level 3 also has sum 15, return 2 since it's the smaller level number.

Input: Root of a binary tree
Output: Integer representing the level with maximum sum

Input & Output

example_1.py โ€” Basic Tree
$ Input: [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 level with maximum sum is level 2 with sum = 7.
example_2.py โ€” Negative Root
$ Input: [-100,-200,-300]
โ€บ Output: 3
๐Ÿ’ก Note: Level 1 sum = -100. Level 2 sum = -200 + (-300) = -500. The level with maximum sum is level 1 with sum = -100.
example_3.py โ€” Single Node
$ Input: [1]
โ€บ Output: 1
๐Ÿ’ก Note: Only one level exists with sum = 1, so return level 1.

Constraints

  • The number of nodes in the tree is in the range [1, 104]
  • -105 โ‰ค Node.val โ‰ค 105
  • Level numbering starts from 1 (root level)

Visualization

Tap to expand
Floor 1: Revenue = $1Room A: $7Room B: $0Room C: $7Room D: -$8Floor Revenue Summary:Floor 1: $1Floor 2: $7 โ† MAXIMUMFloor 3: -$1๐Ÿ† Most Profitable: Floor 2๐Ÿจ Hotel Revenue by Floor AnalysisBFS processes each floor completely before moving to the next floor
Understanding the Visualization
1
Start at Ground Floor
Begin BFS at the root (ground floor lobby)
2
Process Each Floor
For each floor, sum all room revenues (node values)
3
Track Maximum
Keep track of which floor has the highest total revenue
4
Move to Next Floor
Process children nodes (rooms on the next floor up)
5
Return Best Floor
Return the floor number with maximum revenue
Key Takeaway
๐ŸŽฏ Key Insight: BFS naturally processes tree nodes level by level, making it perfect for calculating level sums in a single traversal. This gives us O(n) time complexity - optimal for this problem!
Asked in
Amazon 15 Microsoft 12 Google 8 Meta 6
24.7K Views
Medium Frequency
~15 min Avg. Time
892 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