Tree Height After Deletions

Asked at SnowflakePhone screen

Reported by the problem's creator, not verified

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.

Examples

  1. Example 1

    Input: 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]

    Explanation: 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.

Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question

Code

Loading editor…

Ln 1, Col 1

Start an attempt to use Coach.