489. Heaviest Floor
A stadium is built as a binary tree of seating sections: the root is the first level, its children form the second level, and so on. Each node stores the revenue collected for one section, which may be negative after refunds. The revenue of a level is the sum of the values of all nodes on that level.
Given the root of the tree as root, return the 1-based number of the level with the largest revenue. If several levels share the largest revenue, return the smallest level number among them. For an empty tree, return 0.
Example 1
- Input:
- root = [2,-5,9,7,null,1,4]
- Output:
- 3
- Explanation:
The level sums are 2, 4 and 12, so level 3 is the heaviest.
Example 2
- Input:
- root = [-5,2,6,-1]
- Output:
- 2
- Explanation:
The level sums are -5, 8 and -1, so level 2 is the heaviest.
Example 3
- Input:
- root = [4,3,1]
- Output:
- 1
- Explanation:
Levels 1 and 2 both sum to 4, and the smaller level number is returned.
Constraints
0 ≤ number of nodes ≤ 105
-104 ≤ Node.val ≤ 104
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)