1631. Plant the Forest
A gardener has n seedlings labelled 0 to n - 1; the seedling labelled i carries the value i. The array parent says where each one is grafted: parent[i] is the label of the seedling it hangs from, or -1 if it is planted on its own as a root. For a grafted seedling, side[i] is 0 if it becomes the left child of its parent and 1 if it becomes the right child; for a root, side[i] carries no meaning.
No parent receives two children on the same side and the grafts never form a cycle. Build all the binary trees and return their roots as an array sorted by value ascending. The labels in parent may be larger than the index that mentions them. Runs in O(n) time and O(n) space.
Example 1
- Input:
- parent = [-1,0,0,1,1], side = [0,0,1,0,1]
- Output:
- [[0,1,2,3,4]]
- Explanation:
The result is [[0, 1, 2, 3, 4]].
Example 2
- Input:
- parent = [-1,-1,0,1,-1], side = [0,0,0,1,1]
- Output:
- [[0,2],[1,null,3],[4]]
- Explanation:
The result is [[0, 2], [1, null, 3], [4]].
Constraints
1 ≤ n ≤ 500; parent.length == side.length == n; no node gets two children on the same side; the links contain no cycle
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)