Tree DP & Rerooting
Independent sets on trees, and answers for every root in O(n).
Maximum independent set is NP-hard on general graphs, and even hard to approximate within ; on a tree, two numbers per vertex solve it in linear time. The reason is structural: a vertex cuts a tree into pieces that never interact. Push that idea to graphs that are merely "tree-like" and you reach treewidth, Courcelle's theorem, and lower bounds saying the known algorithms are probably optimal.
What you’ll learn
- Prove the recurrences for weighted independent set and vertex cover on trees, and evaluate them in without deep recursion.
- Prove that the merge loops of tree knapsack (choose vertices closed under taking parents) run fewer than inner steps, whatever the shape of the tree.
- Compute an answer for every root in by rerooting, with an invertible combine (the sum of distances) and with prefix and suffix aggregates (the farthest vertex).
- Explain dynamic programming over tree decompositions, and state Courcelle's theorem and the SETH-tight bound for independent set.
Independent sets and covers, with proofs
consists of , the subtrees of its children, and the edges . There is no edge between two different subtrees and . So a set is independent iff each piece is independent and, when , no child is in :
. Each piece is an independent set of avoiding , chosen independently of the others; by induction the best one weighs :
. Each piece is any independent set of , again chosen independently; by induction the best weighs :
Each vertex is combined into its parent once, so a children-before-parents order (the reverse of a BFS order) computes everything in time without recursion. On a graph with a cycle the first line fails, since two "subtrees" may share edges, and indeed the problem is NP-hard in general.
Vertex cover comes for free: covers every edge iff is independent, so a minimum-weight cover weighs minus a maximum-weight independent set, on any graph. On trees one can also write its own recurrence, and . For unit weights a greedy rule works too: some minimum cover contains the parent of any leaf (exchange the leaf for its parent), so repeatedly take a leaf's parent and delete both; this matches König's theorem, since trees are bipartite and a minimum cover equals a maximum matching there.
On general graphs, maximum independent set is NP-hard, and approximating it within is NP-hard as well (Håstad, 1999; Zuckerman, 2007). Trees are easy because a single vertex separates them.
Think first A star has a center of weight 5 and four leaves of weight 2 each. What do and give at the center, and what is the answer?
, since no leaf may join the center, and . The answer is : the four light leaves together outweigh the heavy center.
Tree knapsack and the merging bound
Each vertex of a rooted tree has a value, and you must choose exactly vertices so that every chosen vertex's parent is chosen too (courses and their prerequisites, a company and its divisions). Let be the best value of such a set with vertices inside that contains . Start with and merge the children one at a time, like knapsacks:
where "size" counts the vertices merged into 's part so far. Each merge looks quadratic, yet the total is small.
Number the vertices in preorder, visiting each vertex's children in the order in which they are merged. Then 's current part ( and its already merged children's subtrees) is a block of consecutive positions ending at some position , and the next child's subtree is the block .
Map the inner step to the pair of positions : the -th position from the end of the left block and the -th of the right block. This is a bijection between the steps of this merge and the pairs with on the left, on the right and
Any two positions are split between the left and the right block in exactly one merge: the one at their lowest common ancestor that brings the second of them into the same part. So the steps of all merges together count each close pair once:
def tree_knapsack(children, value, K, root=0):
"""Best total value of exactly K vertices, where a chosen vertex's parent is chosen too."""
NEG = float('-inf')
order, dp = [root], {}
for v in order: # BFS order: parents before children
order.extend(children[v])
for v in reversed(order): # children before parents
best = [NEG, value[v]] # best[j]: j vertices of v's part, v among them
for c in children[v]:
dc = dp.pop(c) # dc[b]: b vertices of c's subtree (dc[0] = 0)
new = best + [NEG] * min(len(dc) - 1, K + 1 - len(best))
for a in range(1, len(best)):
for b in range(1, min(len(dc), K + 1 - a)): # a + b <= K
new[a + b] = max(new[a + b], best[a] + dc[b])
best = new
dp[v] = [0] + best[1:] # 0 vertices: take nothing from this subtree
res = dp[root]
return res[K] if K < len(res) else NEGArrays never grow beyond entries, and the inner loops are exactly those counted by the theorem; a brute force over all -subsets agrees on random small trees.
A tree has vertices and . About how many inner steps do the merge loops perform, whatever the tree's shape?
Show the answer
8955
, just under . The naive bound, a product of two subtree sizes per merge, would suggest something quadratic; capping the arrays at and the sums at is what makes the total linear in .
Rerooting: every vertex as the root
Many questions ask for an answer per vertex: the sum of distances from each vertex, the farthest vertex from each vertex, the best place for a warehouse. Rooting the tree at each vertex in turn costs per root, in all. Rerooting does it in with two passes: a down pass computes, for every , a summary of its own subtree, and an up pass computes , the same summary for everything outside 's subtree, seen from through its parent. The answer at combines and .
Invertible combines. For the sum of distances the up pass needs no extra structure: moving the root from to its child brings vertices one step closer and pushes one step away, so . A child's own contribution is subtracted from its parent's total, which works because sums can be undone.
Non-invertible combines. For the farthest vertex, the summary is a maximum, and a maximum cannot be undone: knowing over all children does not tell you the maximum over all children but one. Keep, for each vertex, prefix and suffix maxima over its list of children; the siblings of the -th child are then a prefix and a suffix, combined in .
Down pass: is the height of 's subtree (0 for a leaf), computed children first:
Up pass, parents first: a longest path from child that leaves 's subtree takes the edge and then either continues upward from or enters a sibling :
With prefix maxima and suffix maxima over the children of , the maximum over the siblings of is , so the up pass costs at and in total. The eccentricity of , its distance to the farthest vertex, is
def eccentricities(n, adj, root=0):
"""Farthest distance from every vertex: rerooting with prefix and suffix maxima, O(n)."""
parent, order = [-1] * n, [root]
for v in order: # BFS order: parents before children
for c in adj[v]:
if c != parent[v]:
parent[c] = v
order.append(c)
down = [0] * n # down[v]: height of v's subtree
for v in reversed(order):
if parent[v] >= 0:
down[parent[v]] = max(down[parent[v]], down[v] + 1)
up = [0] * n # up[v]: longest path leaving v through its parent
for v in order:
kids = [c for c in adj[v] if c != parent[v]]
vals = [down[c] + 1 for c in kids]
pre, suf = [0], [0] # running maxima from the left and from the right
for x in vals:
pre.append(max(pre[-1], x))
for x in reversed(vals):
suf.append(max(suf[-1], x))
for i, c in enumerate(kids): # siblings of c: kids[:i] and kids[i+1:]
up[c] = 1 + max(up[v], pre[i], suf[len(kids) - 1 - i])
return [max(down[v], up[v]) for v in range(n)]On the tree above the eccentricities are A 3; B, C 4; D, E, F, G 5; H, I, J 6. The minimum, 3 at A, makes A the tree's center; the maximum, 6, is the diameter. Agrees with one BFS per vertex on random trees.
Rerooting the sum of distances needs no prefix or suffix arrays, but rerooting the farthest distance does. Why?
- Maxima are slower to compute than sums
- A sum can be undone by subtraction, but a maximum cannot: removing one child's value from the maximum over all children needs the other children's values
- The farthest distance needs two passes, the sum only one
- Because the farthest vertex may lie outside the tree
Show the answer
B. A sum can be undone by subtraction, but a maximum cannot: removing one child's value from the maximum over all children needs the other children's values
To compute you need the parent's combined value over everything except 's subtree. With sums, subtract 's contribution; with maxima there is no inverse, so precomputed prefix and suffix maxima over the children supply "all siblings except " in .
Beyond trees: treewidth
Condition (3) makes every bag a separator: the parts of the graph below and above a node interact only through its bag. So tree DP generalizes, with a table indexed by what happens inside the bag. For maximum independent set, store for each node and each independent the best weight of an independent set of the part below that meets exactly in . With a nice decomposition, whose nodes only introduce one vertex, forget one vertex, or join two identical bags, each node's table is filled from its children's in time for width :
A tree is the case : bags , and the table is exactly .
The fine print matters. The decomposition must be found: deciding is NP-hard when is part of the input (Arnborg, Corneil & Proskurowski, 1987), but for each fixed Bodlaender (1996) finds a decomposition of width in linear time, with a factor ; Korhonen (FOCS 2021) gives a width- decomposition in time. And the hidden constant of Courcelle's theorem grows as a tower of exponentials in the size of ; Frick and Grohe (2004) showed this is unavoidable even on trees, unless P = NP. Courcelle's theorem classifies problems; hand-written DPs solve them. See Parameterized Algorithms & Kernelization for the wider picture.
Key takeaways
- On a tree, a vertex separates its children's subtrees completely, so and solve weighted independent set (and, by complement, vertex cover) in .
- Tree knapsack's merges, with arrays and sums capped at , perform exactly steps: each step is a pair of vertices less than apart in preorder.
- Rerooting gives every vertex's answer in : a down pass, then an up pass that excludes one child, by subtraction when the combine is invertible and by prefix and suffix aggregates when it is not.
- Tree DP extends to tree decompositions: independent set in , Courcelle's theorem for every MSO property, and SETH says the base 2 is optimal.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why does the recurrence fail on a graph that contains a cycle?
- Because cycles make the graph disconnected
- Because the "subtrees" of different children can be joined by edges, so their choices are no longer independent
- Because a vertex can then have more than two children
- It does not fail; it just runs in time
Show the answer
B. Because the "subtrees" of different children can be joined by edges, so their choices are no longer independent
The proof used one fact: there is no edge between and for different children. A cycle creates such edges, so optimal choices in two parts can conflict. That is why the problem becomes NP-hard on general graphs.
In tree knapsack with (no effective cap), how many inner steps do the merge loops take on a tree with vertices?
- on balanced trees, on paths
- Exactly , whatever the shape
- in the worst case
- on stars only, otherwise
Show the answer
B. Exactly , whatever the shape
Each pair of vertices is combined in exactly one merge, at their lowest common ancestor, so the total is the number of pairs, , for every tree.
A tree has vertices; the distances from vertex to all vertices sum to 640, and its child has a subtree of 30 vertices. What is the sum for ?
- 600
- 610
- 680
- 710
Show the answer
C. 680
: 30 vertices come one step closer and 70 move one step farther.
You must find a maximum independent set in a graph with vertices, given a tree decomposition of width 12. Which statement is right?
- The problem is NP-hard, so nothing better than about is possible
- A DP over the decomposition runs in about time, and under SETH the base 2 cannot be lowered to
- A DP over the decomposition runs in time
- Courcelle's theorem gives an algorithm whose constant is small enough to use directly
Show the answer
B. A DP over the decomposition runs in about time, and under SETH the base 2 cannot be lowered to
Each bag has at most 13 vertices, so each node's table has at most entries: the running time is exponential in the width only, and linear in . Lokshtanov, Marx and Saurabh showed that would refute SETH.
Further reading
- B. Courcelle, "The monadic second-order logic of graphs I. Recognizable sets of finite graphs," Information and Computation 85(1) (1990), 12–75.
- H. L. Bodlaender, "A linear-time algorithm for finding tree-decompositions of small treewidth," SIAM Journal on Computing 25(6) (1996), 1305–1317.
- D. Lokshtanov, D. Marx & S. Saurabh, "Known algorithms on graphs of bounded treewidth are probably optimal," SODA 2011; ACM Transactions on Algorithms (2018).
- M. Cygan, F. V. Fomin, Ł. Kowalik, D. Lokshtanov, D. Marx, M. Pilipczuk, M. Pilipczuk & S. Saurabh, Parameterized Algorithms (Springer, 2015), chapter 7, "Treewidth".
- A. Laaksonen, Competitive Programmer's Handbook (2018), chapter 14, "Tree algorithms" (free online).