1663. Cut the Rising Edges
A family tree is stored as a binary tree where each node holds an age-like score. A feud splits every household in which a child scores strictly higher than its parent: the link between that parent and that child is cut, and the child becomes the head of a separate tree that keeps its own subtree (after that subtree has been cut in the same way).
Return the heads of all resulting trees: the original root first, then every cut-off child. Order the heads by the position of each head in a preorder walk (node, left subtree, right subtree) of the original tree. Each returned tree is serialised from its head in level order by the judge. Equal scores are not cut. Aim for O(n) time and O(h) extra space for the traversal, with iterative traversal recommended.
Example 1
- Input:
- root = [6,3,8,9,2,4,10]
- Output:
- [[6,3,null,null,2],[9],[8,4],[10]]
- Explanation:
Edges 6-8, 3-9 and 8-10 rise and are cut, giving trees headed by 6, 9, 8 and 10 in their preorder positions.
Example 2
- Input:
- root = [5,5,5]
- Output:
- [[5,5,5]]
- Explanation:
All scores are equal, so no child is strictly greater than its parent and nothing is cut.
Constraints
1 ≤ nodes ≤ 500; -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(h)