Root-to-Leaf Cut
GoogleHard
A tree contains n nodes numbered 0 to n - 1 and is rooted at node 0. Each node has at most two children, and edges[k] = [parent, child, weight] describes one directed edge from parent down to its child; the order of edges carries no meaning. A leaf is a node with no children.
You may delete edges. After the deletions, following the remaining edges downward from the root must not reach any leaf of the original tree. Deleting an edge costs its weight, and the total cost is the sum over all deleted edges. Return the smallest possible total cost. With n == 1 the tree has no edges, so the answer is 0.
Part 1: Nonnegative weights
Every weight is zero or positive. Choose edges to remove so that no leaf is reachable from the root, paying the lowest total weight.
- Example 1
- n
7- edges
[[0,1,9],[0,2,5],[1,3,2],[1,4,4],[2,5,1],[2,6,7]]- Output
11
Why: Under node 1, cutting both leaf edges costs 2 + 4 = 6, cheaper than the edge 0 to 1 (9). Under node 2, cutting the edge 0 to 2 costs 5, cheaper than 1 + 7 = 8. The total is 6 + 5 = 11.
Constraints
1 <= n <= 10^4len(edges) == n - 10 <= edges[k][2] <= 10^9edgesforms a single tree rooted at node0edgesgives each node at most two children