Tree Dynamic Programming
Root the tree, give each node a few numbers that summarise its subtree, and compute them children first. A second, top-down pass answers the question for every possible root.
What Tree Dynamic Programming Is
- Root the tree at any node
- Decide what each node must report to its parent
- Write how a node combines its children's reports
- Set the leaf values
- Run a post-order DFS and read the answer at the root
Tree dynamic programming computes an answer for every subtree, using the answers of that node's children. Root the tree at any node. Each node's subtree is then separate from its siblings' subtrees: they share no node and no edge. So a node can combine its children's answers without counting anything twice.
The order is fixed by the tree: children before parents, which is a post-order traversal. Each node is handled once and each edge is looked at twice, so most problems of this kind, often called DP on trees, run in O(n).
- Subtrees of different children never overlap
- Children are finished before their parent
- One pass, O(n) time for constant-size states
Choosing the State
The hardest part is deciding what each node reports. The rule: include exactly what the parent's choice depends on, and nothing more. If the parent only needs to know whether this node was used, two numbers are enough.
Common states: the subtree size; the best value with the node taken and with it left out; the longest downward path from the node (for tree diameter and Binary Tree Maximum Path Sum); the number of ways to colour the subtree given the node's colour.
A state that is too small gives wrong answers. One "best size" per node cannot tell the parent whether the child was used, so the parent may pick both. The fix is not more cleverness in the combine step but one more number in the state.
- State = what crosses the edge to the parent
- Too small: wrong answers; too big: wasted work
- Leaves get the identity value of the combine step
Worked Example: Maximum Independent Set in a Tree
An independent set is a set of nodes with no two joined by an edge. Find the largest one in the tree with edges A-B, A-C, B-D, B-E, rooted at A. Each node u gets take[u], the best set in its subtree that includes u, and skip[u], the best that leaves u out.
If u is taken, no child can be: take[u] = 1 + Σ skip[child]. If u is skipped, each child picks its better option: skip[u] = Σ max(take[child], skip[child]). Leaves have take = 1 and skip = 0.
Post-order goes D, E, B, C, A. D and E give (1, 0). B gives take = 1 + 0 + 0 = 1 and skip = 1 + 1 = 2. C gives (1, 0). A gives take = 1 + 2 + 0 = 3 and skip = max(1, 2) + max(1, 0) = 3. The answer is 3. Walking the choices back down gives {A, D, E}; skipping A instead gives {C, D, E}.
- Two numbers per node, filled bottom-up
- Answer = max(take, skip) at the root
- Store or retrace the choices to get the actual nodes
Terms, operations, and practical uses
Structure
- RootAny node chosen to give every edge a parent end and a child end; it does not change the tree.
- SubtreeA node and everything below it; subtrees of different children never share a node.
- Parent argumentPassed to the DFS so it does not walk back along the edge it came from.
Computing
- StateThe numbers a node reports to its parent, such as take and skip.
- Post-orderChildren before parents; every child is finished when its parent combines.
- CombineHow a node builds its state from its children's states, e.g. take = 1 + Σ skip.
Rerooting
- Up passOrdinary tree DP from one root: subtree values and that root's answer.
- Down passTurns a parent's answer into each child's answer in O(1).
- Prefix and suffixResults over a node's children kept so one child can be excluded when the combine has no inverse.
Code in Python, C++ and Java
def dfs_order(adj, root):
parent = [-1] * len(adj)
order, stack = [], [root]
while stack:
u = stack.pop()
order.append(u)
for v in adj[u]:
if v != parent[u]:
parent[v] = u
stack.append(v)
return order, parent
def max_independent_set(adj):
order, parent = dfs_order(adj, 0)
take, skip = [1] * len(adj), [0] * len(adj)
for u in reversed(order):
p = parent[u]
if p >= 0:
take[p] += skip[u]
skip[p] += max(take[u], skip[u])
return max(take[0], skip[0])
def distance_sums(adj):
n = len(adj)
order, parent = dfs_order(adj, 0)
size, down = [1] * n, [0] * n
for u in reversed(order):
p = parent[u]
if p >= 0:
size[p] += size[u]
down[p] += down[u] + size[u]
ans = [0] * n
ans[0] = down[0]
for u in order[1:]:
ans[u] = ans[parent[u]] - size[u] + (n - size[u])
return ans
adj = [[1, 2], [0, 3, 4], [0], [1], [1]]
print("Maximum independent set:", max_independent_set(adj))
print("Distance sums:", *distance_sums(adj))#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
void dfsOrder(const vector<vector<int>>& adj, int root, vector<int>& order, vector<int>& parent) {
parent.assign(adj.size(), -1);
vector<int> stack = {root};
while (!stack.empty()) {
int u = stack.back();
stack.pop_back();
order.push_back(u);
for (int v : adj[u])
if (v != parent[u]) {
parent[v] = u;
stack.push_back(v);
}
}
}
int maxIndependentSet(const vector<vector<int>>& adj) {
vector<int> order, parent;
dfsOrder(adj, 0, order, parent);
vector<int> take(adj.size(), 1), skip(adj.size(), 0);
for (int i = order.size() - 1; i >= 0; i--) {
int u = order[i], p = parent[u];
if (p >= 0) {
take[p] += skip[u];
skip[p] += max(take[u], skip[u]);
}
}
return max(take[0], skip[0]);
}
vector<long long> distanceSums(const vector<vector<int>>& adj) {
int n = adj.size();
vector<int> order, parent;
dfsOrder(adj, 0, order, parent);
vector<long long> size(n, 1), down(n, 0), ans(n, 0);
for (int i = n - 1; i >= 0; i--) {
int u = order[i], p = parent[u];
if (p >= 0) {
size[p] += size[u];
down[p] += down[u] + size[u];
}
}
ans[0] = down[0];
for (int i = 1; i < n; i++) {
int u = order[i];
ans[u] = ans[parent[u]] - size[u] + (n - size[u]);
}
return ans;
}
int main() {
vector<vector<int>> adj = {{1, 2}, {0, 3, 4}, {0}, {1}, {1}};
cout << "Maximum independent set: " << maxIndependentSet(adj) << "\n";
cout << "Distance sums:";
for (long long x : distanceSums(adj)) cout << " " << x;
cout << "\n";
}import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.List;
public class Main {
static List<Integer> order;
static int[] parent;
static void dfsOrder(int[][] adj, int root) {
order = new ArrayList<>();
parent = new int[adj.length];
Arrays.fill(parent, -1);
Deque<Integer> stack = new ArrayDeque<>();
stack.push(root);
while (!stack.isEmpty()) {
int u = stack.pop();
order.add(u);
for (int v : adj[u])
if (v != parent[u]) {
parent[v] = u;
stack.push(v);
}
}
}
static int maxIndependentSet(int[][] adj) {
dfsOrder(adj, 0);
int[] take = new int[adj.length], skip = new int[adj.length];
Arrays.fill(take, 1);
for (int i = order.size() - 1; i >= 0; i--) {
int u = order.get(i), p = parent[u];
if (p >= 0) {
take[p] += skip[u];
skip[p] += Math.max(take[u], skip[u]);
}
}
return Math.max(take[0], skip[0]);
}
static long[] distanceSums(int[][] adj) {
int n = adj.length;
dfsOrder(adj, 0);
long[] size = new long[n], down = new long[n], ans = new long[n];
Arrays.fill(size, 1);
for (int i = n - 1; i >= 0; i--) {
int u = order.get(i), p = parent[u];
if (p >= 0) {
size[p] += size[u];
down[p] += down[u] + size[u];
}
}
ans[0] = down[0];
for (int i = 1; i < n; i++) {
int u = order.get(i);
ans[u] = ans[parent[u]] - size[u] + (n - size[u]);
}
return ans;
}
public static void main(String[] args) {
int[][] adj = {{1, 2}, {0, 3, 4}, {0}, {1}, {1}};
System.out.println("Maximum independent set: " + maxIndependentSet(adj));
StringBuilder sb = new StringBuilder("Distance sums:");
for (long x : distanceSums(adj)) sb.append(" ").append(x);
System.out.println(sb);
}
}Step through it
Running on edges A-B, A-C, B-D, B-E (0-1, 0-2, 1-3, 1-4), rooted at A
The Rerooting Technique
Some problems ask for an answer with each node as the root, such as the sum of distances from every node to all others. Running the DP from each root costs O(n) each, O(n²) in total. The rerooting technique does it in two passes.
Pass 1 is ordinary tree DP from one root: subtree sizes and the answer for that root. Pass 2 goes top-down and turns a parent's answer into its child's. For distance sums, moving the root from p to child c brings c's size[c] nodes one step closer and pushes the other n − size[c] one step further: ans[c] = ans[p] − size[c] + (n − size[c]).
On the example tree, sizes are A 5, B 3, C 1, D 1, E 1, and the sum from A is 6. Then B = 6 − 3 + 2 = 5, C = 6 − 1 + 4 = 9, D = E = 5 − 1 + 4 = 8. For combines without an inverse, such as max, keep prefix and suffix results over a node's children so that one child can be left out.
- Pass 1, up: subtree values and the root's answer
- Pass 2, down: child's answer from the parent's in O(1)
- O(n) for all n roots instead of O(n²)
Classic Tree DP Problems
These follow the same pattern, differing only in the state.
| Problem | State per node | Combine |
|---|---|---|
| Maximum independent set (House Robber III) | take, skip | take = value + Σ skip; skip = Σ max |
| Minimum vertex cover | in cover, not in cover | not in cover forces every child in |
| Longest path through a node | longest downward path | sum of the two longest child paths |
| Binary Tree Cameras | covered, has camera, needs cover | three cases per child |
| Sum of distances to all nodes | size, distance sum | rerooting pass |
- Vertex cover = n − maximum independent set on any tree
- Weighted versions add the node's value instead of 1
- See Diameter of Binary Tree for the longest-path state
Implementation and Pitfalls
Recursion with a parent argument is the shortest code: dfs(u, parent) visits every neighbour except parent. On a chain of 100,000 nodes that recursion is 100,000 deep, which overflows Python's default limit and can overflow a C++ stack. An iterative version records nodes in DFS order with an explicit stack and then processes that order backwards, which is post-order.
Tree DP needs a real tree: connected, with n − 1 edges. A cycle breaks the separation of subtrees, and a parent check alone cannot stop a loop around a longer cycle. For a forest, run the DP from one root in each component and combine the results.
- Skip the parent, or the search walks back up forever
- Deep chains: use an iterative post-order
- One number too few in the state gives a wrong answer silently
- Check small cases against brute force over all subsets