Dynamic Programming · Pattern 10 of 12

Tree DP: answers from the children up

Root the tree. Each node returns a small tuple of answers for its subtree (for example "with the edge to my parent kept" and "without it"), built from its children's tuples. Process children before parents.

1 variation · 1 problem

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • The input is a tree and you choose nodes or edges under a local rule
  • A node's choice only interacts with its parent and children
  • Something like "at most k edges per node" or "no two adjacent chosen"

The template

Tree DP
// Maximize Sum of Weights after Edge Removals: every node keeps at most k edges
long maximizeSumOfWeights(int[][] edges, int k) {
    int n = edges.length + 1;
    List<int[]>[] adj = new List[n];
    for (int i = 0; i < n; i++) adj[i] = new ArrayList<>();
    for (int[] e : edges) { adj[e[0]].add(new int[]{e[1], e[2]}); adj[e[1]].add(new int[]{e[0], e[2]}); }
    int[] order = new int[n], parent = new int[n];   // BFS order: parents before children
    parent[0] = -1;
    for (int head = 0, tail = 1; head < tail; head++)
        for (int[] e : adj[order[head]])
            if (e[0] != parent[order[head]]) { parent[e[0]] = order[head]; order[tail++] = e[0]; }
    // free[u]: best in u's subtree keeping <= k child edges; busy[u]: <= k - 1 (the parent edge is kept)
    long[] free = new long[n], busy = new long[n];
    for (int idx = n - 1; idx >= 0; idx--) {        // reverse BFS order: children first
        int u = order[idx];
        long base = 0;
        List<Long> gains = new ArrayList<>();
        for (int[] e : adj[u]) {
            if (e[0] == parent[u]) continue;
            base += free[e[0]];                      // drop the edge to this child
            long gain = e[1] + busy[e[0]] - free[e[0]];   // extra from keeping it
            if (gain > 0) gains.add(gain);
        }
        gains.sort(Collections.reverseOrder());      // keep the biggest gains first
        free[u] = busy[u] = base;
        for (int i = 0; i < gains.size() && i < k; i++) {
            free[u] += gains.get(i);
            if (i < k - 1) busy[u] += gains.get(i);
        }
    }
    return free[0];
}

The variations

  1. 1Keep or drop each child edge

    Dropping the edge to child c is worth free[c]; keeping it is worth w + busy[c], because c then has one fewer edge to spend. Start from all dropped and add the biggest positive gains: up to k of them for free[u], up to k - 1 for busy[u].

Mistakes to avoid

  • Recursing on a long path tree with 10^5 nodes: the stack overflows (especially in Python). Process nodes in reverse BFS order instead.
  • Returning one number per node when the parent needs two: the answer with and without the parent edge (or node) used.
  • Summing weights in a 32-bit int: the total can pass 2^31 - 1.
Next: Bitmask DP: a subset as the state →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.