KatInterview

Tree Depth After Splicing Out Removed Nodes

Trees & GraphsAuto-graded · 26 test cases
MediumAuto-gradedTrees & Graphstreebfsparent-array

Last updated

Compute the depth of a rooted tree given as a parent array after splicing out marked nodes, so their children attach to the nearest surviving ancestor.

Tree Depth After Splicing Out Nodes

A rooted tree with n nodes labeled 0 to n - 1 is described by a parent array. Some nodes are marked for removal. Removing a node does not discard its subtree. Instead, the node is spliced out, and each of its children is reattached to the removed node's parent. If that parent is also removed, the children keep climbing until they reach the closest ancestor that is not removed.

Return the depth of the tree after all the removals, measured as the number of nodes on the longest root-to-node path.

Details

  • Node 0 is the root and parent[0] == -1. For every other node i, parent[i] is its parent. A parent may have a larger index than its child.
  • The root is never removed.
  • The final result does not depend on the order in which the removals are applied.
  • Depth counts nodes, not edges. A tree consisting of only the root has depth 1.

Function

Implement tree_depth_after_removals(parent, removed), where parent is the parent array and removed is the list of nodes to splice out. Return an integer.

Constraints

  • 1 <= n == len(parent) <= 10^5
  • parent[0] == -1; for i >= 1, 0 <= parent[i] <= n - 1, and the links form a single tree rooted at 0 with no cycles.
  • 0 <= len(removed) <= n - 1
  • Values in removed are distinct and lie between 1 and n - 1.
  • The tree may be a single path, so its depth can be as large as n.

Examples

Example 1

Input: tree_depth_after_removals([-1, 0, 0, 1, 1, 3, 2], [1])

Output: 3

Example 2

Input: tree_depth_after_removals([-1, 0, 0, 1, 1, 3, 2], [1, 3, 2])

Output: 2

Example 3

Input: tree_depth_after_removals([-1, 0, 0, 1, 1, 3, 2], [])

Output: 4

Hints

Hint 1

Try not to simulate the reattachment. Ask what a surviving node's depth is in terms of its original ancestors.

Hint 2

A surviving node's new depth equals the number of non-removed nodes on its original root-to-node path, including itself and the root.

Hint 3

Build a children list and traverse from the root iteratively (parents can have larger indices, and the tree can be 10^5 deep). A removed child inherits its parent's depth; a surviving child adds 1.