1635. Slanted Layers
A garden is laid out as a binary tree. Draw each node on a slanted layer: the root sits on layer 0, a right child stays on the same layer as its parent, and a left child moves one layer up (parent layer + 1).
Given root, return a 2D array result where result[d] holds the values on layer d, for d = 0, 1, 2, ... until no nodes remain. Inside one layer, list the values in preorder order: a node comes before its left subtree, and its left subtree comes before its right subtree.
The tree always has at least one node. Aim for O(n) time and O(n) extra space, and prefer an explicit stack over recursion so that a very long chain of nodes cannot overflow the call stack.
Example 1
- Input:
- root = [5,3,8,1,4,7,9]
- Output:
- [[5,8,9],[3,4,7],[1]]
- Explanation:
Layer 0 is the right chain 5, 8, 9; layer 1 holds 3, 4 and 7 (preorder order); layer 2 holds 1.
Example 2
- Input:
- root = [1,null,2,null,3]
- Output:
- [[1,2,3]]
- Explanation:
Every node is a right child, so all three stay on layer 0.
Example 3
- Input:
- root = [4,2,null,1]
- Output:
- [[4],[2],[1]]
- Explanation:
Each node is the left child of the previous one, giving one node per layer.
Constraints
1 ≤ nodes ≤ 1000
-1000 ≤ Node.val ≤ 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 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)