KatInterview

Prune Minimum Nodes from Tree to Satisfy Height Budget

Dynamic ProgrammingModel answer
MediumModel answerDynamic Programmingtrees-graphsdynamic-programmingtree-dp

Last updated

Determine the minimal set of non-root node deletions required to trim a multi-child tree's height down to a target limit under node-promotion rules.

Given a rooted general tree (where each node can have multiple children) and a maximum target height $H$, identify a set containing the minimum number of node deletions required so that the height of the modified tree does not exceed $H$.

When a non-root node is deleted, it is removed from the tree and all of its direct children are promoted to become direct children of its parent (i.e., its subtrees are preserved and moved up one level). The root node (ID 0) cannot be deleted under any circumstances.

Input Specifications

  • parent: An array of length $M$ representing the tree topology, where parent[i] is the ID of the parent of node i. Node 0 is always the root, so parent[0] = -1.
  • H: A positive integer representing the maximum allowable height. Height is defined as the total number of retained nodes along the longest path from the root to any leaf (e.g., a tree with only the root node has height 1).

Constraints

  • $1 \le M \le 1000$
  • $1 \le H \le M$
  • Node IDs are integers from 0 to $M-1$.
  • Any valid minimal-cardinality set of node IDs to delete may be returned in any order.

Example 1

Input: parent = [-1, 0, 0], H = 1
Output: [1, 2]
Explanation: Node 0 is the root with children 1 and 2. To reach height 1, both child nodes must be removed.

Example 2

Input: parent = [-1, 0, 1, 1], H = 2
Output: [1]
Explanation: Node 0 is parent of 1, and node 1 is parent of 2 and 3. Retaining node 1 gives height 3 (0 -> 1 -> 2). Deleting node 1 promotes 2 and 3 to be direct children of 0, yielding a tree of height 2 (0 -> 2 and 0 -> 3) using 1 deletion. Deleting {2, 3} also achieves height 2 but requires 2 deletions. Thus, [1] is optimal.

Hints

Hint 1

Tree Dynamic Programming: For each node, compute the minimum cost (deletions) to limit the height of its subtree under different allowed height budgets.

Hint 2

Child Promotion Semantics: If you delete a node u, its height contribution to its parent is the height of its subtrees without adding +1 for node u.

Hint 3

State Definition: Define dp(u, h) as the minimum deletions needed in node u's subtree such that the maximum height of the subtree rooted at u is at most h.