You are given a rooted tree with n nodes labeled from 0 to n - 1, where node 0 is the root. The tree is described by an array parent of length n, where parent[i] is the parent of node i, and parent[0] = -1.
Initially, only the root has a piece of information. In each iteration, every node that already has the information may pass it to at most one of its direct children. Once a child receives the information, it can begin passing it on starting from the next iteration.
Return the minimum number of iterations required so that every node in the tree has received the information.
Function Signature
def min_iterations(parent: list[int]) -> int:
Rules
-
Information only moves from a node to one of its direct children, never to a parent or a sibling.
-
All informed nodes act in the same iteration, independently of each other.
-
A node that receives the information during iteration
j
can first pass it on during iteration
j + 1
.
-
A tree with a single node needs
0
iterations.
Constraints
-
1 <= n <= 10^5
-
len(parent) == n
-
parent[0] == -1
(node
0
is the root)
-
0 <= parent[i] < n
for all
i >= 1
-
The input forms a valid rooted tree.
Examples
Input: parent = [-1, 0, 0, 0, 1, 1, 2]
Output: 3
Tree:
0
/ | \
1 2 3
/ \ |
4 5 6
The root informs 1, 2 and 3 in iterations 1, 2 and 3. Meanwhile node 1 informs 4 and 5 in iterations 2 and 3, and node 2 informs 6 in iteration 3. The root has three children and can reach only one per iteration, so fewer than 3 iterations is impossible.
Input: parent = [-1, 0, 0, 1, 1, 2, 2, 3, 3]
Output: 4
Tree:
0
/ \
1 2
/ \ / \
3 4 5 6
/ \
7 8
The root informs 1 in iteration 1 and 2 in iteration 2. Node 1 informs 3 in iteration 2 and 4 in iteration 3, node 3 informs 7 and 8 in iterations 3 and 4, and node 2 informs 5 and 6 in iterations 3 and 4. Informing 2 first would leave node 1's larger subtree finishing in iteration 5.
Input: parent = [-1, 0, 1, 2]
Output: 3
The tree is a chain 0, 1, 2, 3, so the information moves down one level per iteration.