Subtree Pruning I
A rooted tree with n nodes, 0 to n - 1, is given as a parent array: one entry is -1, marking the root, and every other parent[i] is the parent of node i. The root has depth 0.
Deleting a node removes it and its whole subtree. You are given the nodes to delete; the root may be among them, a node may be listed twice, and a listed node may already sit inside another deleted subtree.
Return the largest original depth among the nodes that remain, or -1 when nothing does.
deepestRemaining(6, [-1, 0, 0, 1, 1, 3], [3]) -> 2 // 3 takes 5 with it; 4 is left at depth 2 deepestRemaining(1, [-1], [0]) -> -1
Hints
Hint 1
Build children lists and walk from the root; a deleted node is simply never entered, so its subtree never counts.
Hint 2
Depths come from the walk itself — the parent array need not list parents before children.
Topics
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.