You are given a rooted tree with n nodes labeled 0 to n - 1, represented as a parent array parent, where parent[i] is the parent of node i. Node 0 is the root and parent[0] = -1. A node may have any number of children, and a parent is not required to have a smaller ID than its child.
The tree is deleted in rounds. In each round, all nodes that are currently leaves (nodes with no remaining children) are removed simultaneously. This repeats until the tree is empty. The root is removed in the final round.
Return the removed node IDs as a single flattened integer list: all nodes removed in round 1 come first, followed by those removed in round 2, and so on. Within a single round, node IDs must appear in ascending order.
Function Signature
def leaf_removal_order(parent: list[int]) -> list[int]:
Rules
-
parent[i]
is the parent of node
i
. Node
0
is the root and
parent[0] == -1
.
-
A node is a leaf in a round when it has no children left, either because it never had any or because all of its children were removed in earlier rounds.
-
Every node appears in the output exactly once. Rounds are listed in order, and IDs inside one round are sorted ascending.
Constraints
-
1 <= n == len(parent) <= 10^5
-
parent[0] == -1
-
0 <= parent[i] <= n - 1
for
1 <= i < n
-
parent[i] != i
-
The input represents exactly one valid tree rooted at node
0
.
Examples
Input: parent = [-1,0,0,1,1,2]
Output: [3,4,5,1,2,0]
Node 0 has children 1 and 2, node 1 has children 3 and 4, and node 2 has child 5. Round 1 removes the leaves 3, 4 and 5, round 2 removes 1 and 2, and round 3 removes the root 0.
Input: parent = [-1,3,3,0,1]
Output: [2,4,1,3,0]
Node 3 is the only child of the root, nodes 1 and 2 are children of 3, and node 4 is a child of 1, so parents can have larger IDs than their children. The rounds remove 2 and 4, then 1, then 3, then 0.
Input: parent = [-1,0,0,2]
Output: [1,3,2,0]
Node 1 hangs directly off the root but has no children, so it is removed in round 1 together with node 3. Node 2 becomes a leaf after node 3 is gone and is removed in round 2, and the root goes in round 3.