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.
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
// 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];
} def maximize_sum_of_weights(edges, k):
n = len(edges) + 1
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w))
adj[v].append((u, w))
order, parent = [0], [-1] * n # BFS order: parents before children
for u in order:
for v, _ in adj[u]:
if v != parent[u]:
parent[v] = u
order.append(v)
# free[u]: best in u's subtree keeping <= k child edges; busy[u]: <= k - 1 (parent edge kept)
free, busy = [0] * n, [0] * n
for u in reversed(order): # children first
base, gains = 0, []
for v, w in adj[u]:
if v == parent[u]:
continue
base += free[v] # drop the edge to this child
gain = w + busy[v] - free[v] # extra from keeping it
if gain > 0:
gains.append(gain)
gains.sort(reverse=True) # keep the biggest gains first
free[u] = base + sum(gains[:k])
busy[u] = base + sum(gains[:k - 1])
return free[0] // Maximize Sum of Weights after Edge Removals: every node keeps at most k edges
long long maximizeSumOfWeights(vector<vector<int>>& edges, int k) {
int n = edges.size() + 1;
vector<vector<pair<int, int>>> adj(n);
for (auto& e : edges) { adj[e[0]].push_back({e[1], e[2]}); adj[e[1]].push_back({e[0], e[2]}); }
vector<int> order = {0}, parent(n, -1); // BFS order: parents before children
for (int h = 0; h < (int)order.size(); h++) {
int u = order[h];
for (auto [v, w] : adj[u]) if (v != parent[u]) { parent[v] = u; order.push_back(v); }
}
// freeK[u]: best in u's subtree keeping <= k child edges; busy[u]: <= k - 1 (parent edge kept)
vector<long long> freeK(n), busy(n);
for (int idx = n - 1; idx >= 0; idx--) { // children first
int u = order[idx];
long long base = 0;
vector<long long> gains;
for (auto [v, w] : adj[u]) {
if (v == parent[u]) continue;
base += freeK[v]; // drop the edge to this child
long long gain = w + busy[v] - freeK[v]; // extra from keeping it
if (gain > 0) gains.push_back(gain);
}
sort(gains.rbegin(), gains.rend()); // keep the biggest gains first
freeK[u] = busy[u] = base;
for (int i = 0; i < (int)gains.size() && i < k; i++) {
freeK[u] += gains[i];
if (i < k - 1) busy[u] += gains[i];
}
}
return freeK[0];
} // Maximize Sum of Weights after Edge Removals: every node keeps at most k edges
function maximizeSumOfWeights(edges, k) {
const n = edges.length + 1, adj = Array.from({ length: n }, () => []);
for (const [u, v, w] of edges) { adj[u].push([v, w]); adj[v].push([u, w]); }
const order = [0], parent = new Array(n).fill(-1); // BFS order: parents before children
for (let h = 0; h < order.length; h++) {
const u = order[h];
for (const [v] of adj[u]) if (v !== parent[u]) { parent[v] = u; order.push(v); }
}
// free[u]: best in u's subtree keeping <= k child edges; busy[u]: <= k - 1 (parent edge kept)
const free = new Array(n).fill(0), busy = new Array(n).fill(0);
for (let idx = n - 1; idx >= 0; idx--) { // children first
const u = order[idx];
let base = 0;
const gains = [];
for (const [v, w] of adj[u]) {
if (v === parent[u]) continue;
base += free[v]; // drop the edge to this child
const gain = w + busy[v] - free[v]; // extra from keeping it
if (gain > 0) gains.push(gain);
}
gains.sort((x, y) => y - x); // keep the biggest gains first
free[u] = busy[u] = base;
for (let i = 0; i < gains.length && i < k; i++) {
free[u] += gains[i];
if (i < k - 1) busy[u] += gains[i];
}
}
return free[0];
} The variations
-
1Keep or drop each child edge
Dropping the edge to child
cis worthfree[c]; keeping it is worthw + busy[c], becausecthen has one fewer edge to spend. Start from all dropped and add the biggest positive gains: up tokof them forfree[u], up tok - 1forbusy[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.
Lesson done
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.