455. Floor by Floor
A hotel's rooms are arranged as a binary tree in root: the lobby is the root, and each room opens onto at most two rooms on the floor below, a left one and a right one. A guide wants to list the rooms floor by floor.
Return a two-dimensional array in which row i holds the values of all nodes at depth i (the root is depth 0), ordered from left to right. Rows are listed from the top floor downwards. For an empty tree return an empty array.
Example 1
- Input:
- root = [4,9,2,null,7,5,null,1]
- Output:
- [[4],[9,2],[7,5],[1]]
- Explanation:
Depth 0 is [4], depth 1 is [9,2], depth 2 is [7,5], and depth 3 is [1].
Example 2
- Input:
- root = [-3,6,null,null,8]
- Output:
- [[-3],[6],[8]]
- Explanation:
The chain -3, 6, 8 produces one value per floor.
Constraints
0 ≤ number of nodes ≤ 105
-1000 ≤ node value ≤ 1000
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 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)