Tree Height After Deletions
SnowflakePhone screenMedium
A rooted tree is given as a parent array over nodes 0 to n - 1. parent[0] == -1 (node 0 is the root) and every other node lists its parent. The array can list nodes in any order, so a child may have a smaller index than its parent.
Deleting a non-root node promotes all of its children to its parent: the children and their subtrees stay in the tree. The height of the tree is the number of retained nodes on the longest root-to-leaf path, so a tree that is only the root has height 1.
Each test drives one TreeTrimmer instance through a sequence of calls and checks every return value. Calls never change the stored tree.
Part 1: Height after deleting given nodes
Implement height_after(deleted), which returns the height of the tree after removing every node listed in deleted as described above.
deleted is a list of non-root node ids, possibly with repeats, and may be empty. The stored tree is not changed, so each call starts from the full tree.
- Example 1
- init
[[-1,0,0,2,2,4]]- operations
[["height_after",[[]]],["height_after",[[2]]],["height_after",[[4]]],["height_after",[[2,4]]],["height_after",[[5]]],["height_after",[[3]]]]- Output
[4,3,3,2,3,4]
Why: Initially the longest path is 0-2-4-5 with 4 nodes. Deleting 2 promotes 3 and 4 to the root, so the longest path is 0-4-5 with 3 nodes. Deleting 2 and 4 attaches 3 and 5 to the root, height 2. Deleting the leaf 5 shortens 0-2-4 to 3 nodes, and deleting leaf 3 changes nothing.
Constraints
1 <= len(parent) <= 2 * 10^5parent[0] == -1and0 <= parent[i] < len(parent)fori > 0parentdescribes a tree rooted at node 01 <= deleted[i] < len(parent)1 <= len(operations) <= 10