Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

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 n1−εn^{1-\varepsilon}; 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 take/skip\mathrm{take}/\mathrm{skip} recurrences for weighted independent set and vertex cover on trees, and evaluate them in O(n)O(n) without deep recursion.
  • Prove that the merge loops of tree knapsack (choose KK vertices closed under taking parents) run fewer than nKnK inner steps, whatever the shape of the tree.
  • Compute an answer for every root in O(n)O(n) 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 2tw2^{\mathrm{tw}} bound for independent set.

Independent sets and covers, with proofs

DerivationProof by induction on the height of v
  1. I independent  ⟺  ∀c: I∩Tc independent, and (v∈I⇒c∉I)I\ \text{independent}\iff \forall c:\ I\cap T_c\ \text{independent, and}\ \big(v\in I\Rightarrow c\notin I\big)

    TvT_v consists of vv, the subtrees TcT_c of its children, and the edges vcvc. There is no edge between two different subtrees TcT_c and Tc′T_{c'}. So a set I⊆TvI\subseteq T_v is independent iff each piece I∩TcI\cap T_c is independent and, when v∈Iv\in I, no child is in II:

  2. take[v]=wv+∑cskip[c]\mathrm{take}[v]=w_v+\sum_{c}\mathrm{skip}[c]

    v∈Iv\in I. Each piece I∩TcI\cap T_c is an independent set of TcT_c avoiding cc, chosen independently of the others; by induction the best one weighs skip[c]\mathrm{skip}[c]:

  3. skip[v]=∑cmax⁡(take[c], skip[c])\mathrm{skip}[v]=\sum_{c}\max\big(\mathrm{take}[c],\ \mathrm{skip}[c]\big)

    v∉Iv\notin I. Each piece is any independent set of TcT_c, again chosen independently; by induction the best weighs max⁡(take[c],skip[c])\max(\mathrm{take}[c],\mathrm{skip}[c]):

  4. T(n)=∑vO(1+#children(v))=O(n)T(n)=\sum_v O\big(1+\#\text{children}(v)\big)=O(n)

    Each vertex is combined into its parent once, so a children-before-parents order (the reverse of a BFS order) computes everything in O(n)O(n) 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: CC covers every edge iff V∖CV\setminus C is independent, so a minimum-weight cover weighs ∑vwv\sum_vw_v minus a maximum-weight independent set, on any graph. On trees one can also write its own recurrence, in[v]=wv+∑cmin⁡(in[c],out[c])\mathrm{in}[v]=w_v+\sum_c\min(\mathrm{in}[c],\mathrm{out}[c]) and out[v]=∑cin[c]\mathrm{out}[v]=\sum_c\mathrm{in}[c]. 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 n1−εn^{1-\varepsilon} 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 take\mathrm{take} and skip\mathrm{skip} give at the center, and what is the answer?

take[center]=5+0=5\mathrm{take}[\text{center}]=5+0=5, since no leaf may join the center, and skip[center]=4⋅max⁡(2,0)=8\mathrm{skip}[\text{center}]=4\cdot\max(2,0)=8. The answer is max⁡(5,8)=8\max(5,8)=8: 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 KK vertices so that every chosen vertex's parent is chosen too (courses and their prerequisites, a company and its divisions). Let dpv[j]\mathrm{dp}_v[j] be the best value of such a set with jj vertices inside TvT_v that contains vv. Start with dpv=[−∞, valuev]\mathrm{dp}_v=[-\infty,\ \mathrm{value}_v] and merge the children one at a time, like knapsacks:

new[a+b]=max⁡(new[a+b], dpv[a]+dpc[b]),1≤a≤min⁡(size,K),  1≤b≤min⁡(sizec,K),  a+b≤K,\mathrm{new}[a+b]=\max\big(\mathrm{new}[a+b],\ \mathrm{dp}_v[a]+\mathrm{dp}_c[b]\big),\qquad 1\le a\le\min(\mathrm{size},K),\ \ 1\le b\le\min(\mathrm{size}_c,K),\ \ a+b\le K,

where "size" counts the vertices merged into vv's part so far. Each merge looks quadratic, yet the total is small.

DerivationProof: every step is a pair of nearby vertices
  1. [ pos(v), …, p ]⏟v’s part so far [ p+1, …, p+s ]⏟child’s subtree\underbrace{[\,\mathrm{pos}(v),\ \dots,\ p\,]}_{v\text{'s part so far}}\ \underbrace{[\,p+1,\ \dots,\ p+s\,]}_{\text{child's subtree}}

    Number the vertices in preorder, visiting each vertex's children in the order in which they are merged. Then vv's current part (vv and its already merged children's subtrees) is a block of consecutive positions ending at some position pp, and the next child's subtree is the block p+1,…,p+sp+1,\dots,p+s.

  2. y−x=a+b−1 ≤ K−1y-x=a+b-1\ \le\ K-1

    Map the inner step (a,b)(a,b) to the pair of positions (x,y)=(p−a+1, p+b)(x,y)=(p-a+1,\ p+b): the aa-th position from the end of the left block and the bb-th of the right block. This is a bijection between the steps of this merge and the pairs with xx on the left, yy on the right and

  3. #steps=#{(x,y): 1≤x<y≤n, y−x≤K−1}=∑d=1K−1(n−d)\#\text{steps}=\#\{(x,y):\ 1\le x<y\le n,\ y-x\le K-1\}=\sum_{d=1}^{K-1}(n-d)

    Any two positions x<yx<y 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:

python
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 NEG

Arrays never grow beyond K+1K+1 entries, and the inner loops are exactly those counted by the theorem; a brute force over all KK-subsets agrees on random small trees.

Predict before you look

A tree has n=1000n=1000 vertices and K=10K=10. About how many inner steps do the merge loops perform, whatever the tree's shape?

Show the answer

8955

∑d=19(1000−d)=9⋅1000−45=8955\sum_{d=1}^{9}(1000-d)=9\cdot1000-45=8955, just under nK=10,000nK=10{,}000. The naive bound, a product of two subtree sizes per merge, would suggest something quadratic; capping the arrays at KK and the sums at KK is what makes the total linear in nn.

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 O(n)O(n) per root, O(n2)O(n^2) in all. Rerooting does it in O(n)O(n) with two passes: a down pass computes, for every vv, a summary down[v]\mathrm{down}[v] of its own subtree, and an up pass computes up[v]\mathrm{up}[v], the same summary for everything outside vv's subtree, seen from vv through its parent. The answer at vv combines down[v]\mathrm{down}[v] and up[v]\mathrm{up}[v].

Invertible combines. For the sum of distances the up pass needs no extra structure: moving the root from pp to its child cc brings size[c]\mathrm{size}[c] vertices one step closer and pushes n−size[c]n-\mathrm{size}[c] one step away, so ans[c]=ans[p]+n−2 size[c]\mathrm{ans}[c]=\mathrm{ans}[p]+n-2\,\mathrm{size}[c]. 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 max⁡\max 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 ii-th child are then a prefix and a suffix, combined in O(1)O(1).

DerivationThe farthest vertex from every vertex
  1. down[v]=max⁡c(down[c]+1)\mathrm{down}[v]=\max_{c}\big(\mathrm{down}[c]+1\big)

    Down pass: down[v]\mathrm{down}[v] is the height of vv's subtree (0 for a leaf), computed children first:

  2. up[c]=1+max⁡(up[v], max⁡s≠c(down[s]+1)),up[root]=0\mathrm{up}[c]=1+\max\Big(\mathrm{up}[v],\ \max_{s\ne c}\big(\mathrm{down}[s]+1\big)\Big),\qquad \mathrm{up}[\text{root}]=0

    Up pass, parents first: a longest path from child cc that leaves cc's subtree takes the edge c vc\,v and then either continues upward from vv or enters a sibling s≠cs\ne c:

  3. ecc(v)=max⁡(down[v], up[v])\mathrm{ecc}(v)=\max\big(\mathrm{down}[v],\ \mathrm{up}[v]\big)

    With prefix maxima pre\mathrm{pre} and suffix maxima suf\mathrm{suf} over the children c1,…,cmc_1,\dots,c_m of vv, the maximum over the siblings of cic_i is max⁡(prei−1,sufi+1)\max(\mathrm{pre}_{i-1},\mathrm{suf}_{i+1}), so the up pass costs O(m)O(m) at vv and O(n)O(n) in total. The eccentricity of vv, its distance to the farthest vertex, is

python
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.

Check your understanding

Rerooting the sum of distances needs no prefix or suffix arrays, but rerooting the farthest distance does. Why?

  1. Maxima are slower to compute than sums
  2. 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
  3. The farthest distance needs two passes, the sum only one
  4. 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 up[c]\mathrm{up}[c] you need the parent's combined value over everything except cc's subtree. With sums, subtract cc's contribution; with maxima there is no inverse, so precomputed prefix and suffix maxima over the children supply "all siblings except cc" in O(1)O(1).

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 tt and each independent S⊆XtS\subseteq X_t the best weight of an independent set of the part below tt that meets XtX_t exactly in SS. 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 O(2kkO(1))O(2^{k}k^{O(1)}) time for width kk:

O(2k kO(1) n) for independent set, given a decomposition of width k.O\big(2^{k}\,k^{O(1)}\,n\big)\ \text{for independent set, given a decomposition of width }k.

A tree is the case k=1k=1: bags {v,parent(v)}\{v,\mathrm{parent}(v)\}, and the table is exactly take/skip\mathrm{take}/\mathrm{skip}.

The fine print matters. The decomposition must be found: deciding tw(G)≤k\mathrm{tw}(G)\le k is NP-hard when kk is part of the input (Arnborg, Corneil & Proskurowski, 1987), but for each fixed kk Bodlaender (1996) finds a decomposition of width kk in linear time, with a factor 2O(k3)2^{O(k^3)}; Korhonen (FOCS 2021) gives a width-(2k+1)(2k+1) decomposition in 2O(k)n2^{O(k)}n time. And the hidden constant of Courcelle's theorem grows as a tower of exponentials in the size of φ\varphi; 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 take[v]=wv+∑skip[c]\mathrm{take}[v]=w_v+\sum\mathrm{skip}[c] and skip[v]=∑max⁡(take[c],skip[c])\mathrm{skip}[v]=\sum\max(\mathrm{take}[c],\mathrm{skip}[c]) solve weighted independent set (and, by complement, vertex cover) in O(n)O(n).
  • Tree knapsack's merges, with arrays and sums capped at KK, perform exactly ∑d=1K−1(n−d)<nK\sum_{d=1}^{K-1}(n-d)<nK steps: each step is a pair of vertices less than KK apart in preorder.
  • Rerooting gives every vertex's answer in O(n)O(n): 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 O(2twtwO(1)n)O(2^{\mathrm{tw}}\mathrm{tw}^{O(1)}n), 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.

Question 1

Why does the take/skip\mathrm{take}/\mathrm{skip} recurrence fail on a graph that contains a cycle?

  1. Because cycles make the graph disconnected
  2. Because the "subtrees" of different children can be joined by edges, so their choices are no longer independent
  3. Because a vertex can then have more than two children
  4. It does not fail; it just runs in O(n2)O(n^2) 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 TcT_c and Tc′T_{c'} 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.

Question 2

In tree knapsack with K=nK=n (no effective cap), how many inner steps do the merge loops take on a tree with nn vertices?

  1. O(nlog⁡n)O(n\log n) on balanced trees, Θ(n2)\Theta(n^2) on paths
  2. Exactly n(n−1)/2n(n-1)/2, whatever the shape
  3. Θ(n3)\Theta(n^3) in the worst case
  4. Θ(n2)\Theta(n^2) on stars only, O(n)O(n) otherwise
Show the answer

B. Exactly n(n−1)/2n(n-1)/2, 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, (n2)\binom n2, for every tree.

Question 3

A tree has n=100n=100 vertices; the distances from vertex pp to all vertices sum to 640, and its child cc has a subtree of 30 vertices. What is the sum for cc?

  1. 600
  2. 610
  3. 680
  4. 710
Show the answer

C. 680

ans[c]=ans[p]+n−2 size[c]=640+100−60=680\mathrm{ans}[c]=\mathrm{ans}[p]+n-2\,\mathrm{size}[c]=640+100-60=680: 30 vertices come one step closer and 70 move one step farther.

Question 4

You must find a maximum independent set in a graph with n=105n=10^5 vertices, given a tree decomposition of width 12. Which statement is right?

  1. The problem is NP-hard, so nothing better than about 2n2^n is possible
  2. A DP over the decomposition runs in about 212⋅poly(12)⋅n2^{12}\cdot\mathrm{poly}(12)\cdot n time, and under SETH the base 2 cannot be lowered to 2−ε2-\varepsilon
  3. A DP over the decomposition runs in O(n⋅12)O(n\cdot12) time
  4. 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 212⋅poly(12)⋅n2^{12}\cdot\mathrm{poly}(12)\cdot n time, and under SETH the base 2 cannot be lowered to 2−ε2-\varepsilon

Each bag has at most 13 vertices, so each node's table has at most 213=81922^{13}=8192 entries: the running time is exponential in the width only, and linear in nn. Lokshtanov, Marx and Saurabh showed that (2−ε)twnO(1)(2-\varepsilon)^{\mathrm{tw}}n^{O(1)} 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).