You are given a tree rooted at node 0 with n nodes labeled from 0 to n - 1, and an array edges where edges[i] = [u, v] represents an undirected edge between nodes u and v.
You are also given an integer k. Find the minimum number of nodes to delete so that the height of the remaining tree is less than or equal to k.
When a node is deleted, its subtrees are not removed. Instead, the children of the deleted node become directly connected to the deleted node's parent. In other words, deleting a node removes it from the path but preserves the rest of the tree structure below it.
The height of a tree is the number of edges on the longest path from the root to any leaf node.
Return the minimum number of deletions required.
Function Signature
def min_deletions(n: int, edges: list[list[int]], k: int) -> int:
Rules
-
Node
0
is the root and cannot be deleted.
-
The edges are undirected. Parent and child follow from rooting the tree at node
0
.
-
All deletions apply together. A remaining node hangs under its nearest remaining ancestor, so if a node and its parent are both deleted, the node's children move up two levels. Equivalently, the depth of a remaining node is the number of remaining non-root nodes on its original path from the root, itself included.
-
Deleting a leaf simply removes it.
-
A tree that is only the root has height
0
.
Constraints
-
1 <= n <= 10^5
-
0 <= k <= n - 1
-
edges.length == n - 1
-
0 <= edges[i][0], edges[i][1] < n
-
The input forms a valid tree rooted at node
0
.
Examples
Input: n = 7, edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]], k = 1
Output: 2
0
/ \
1 2
/ \ / \
3 4 5 6
The tree has height 2. Deleting nodes 1 and 2 attaches 3, 4, 5 and 6 directly to node 0, which gives height 1. A single deletion always leaves a path such as 0-2-5 or 0-1-3 with two edges.
Input: n = 5, edges = [[0,1],[1,2],[2,3],[3,4]], k = 2
Output: 2
0 - 1 - 2 - 3 - 4
This chain has height 4. Deleting nodes 1 and 3 turns it into 0-2-4, which has height 2. One deletion is not enough: removing any of nodes 1, 2 or 3 leaves node 4 at depth 3, and removing node 4 leaves node 3 at depth 3.
Input: n = 6, edges = [[0,1],[1,2],[1,3],[2,4],[3,5]], k = 2
Output: 1
0
|
1
/ \
2 3
| |
4 5
Deleting node 1 attaches nodes 2 and 3 to the root, so nodes 4 and 5 end at depth 2. The tree has height 3, so at least one deletion is needed. Deleting the deep nodes 4 and 5 instead would cost two.