Tree DP
State is a node (plus a small flag); each node combines the answers of its children in post-order.
You have not marked these as done yet. Read on anyway if they feel familiar; come back to them if something here does not land.
Overview
A rooted tree is already a DAG, so DP on it needs no clever ordering: compute every child before its parent — a post-order Depth-First Search (DFS). The state is dp[v] (often dp[v][flag]) = the best answer for the subtree rooted at v under some condition about v itself: "v is selected / not selected", "path ends at v", "colour of v". The transition aggregates over children: a sum, a max, the two largest values, or a small knapsack merge.
Members: maximum independent set on a tree (House Robber III), tree diameter (largest top1 + top2 of child depths), binary-tree-maximum-path-sum-style problems, minimum vertex cover / dominating set, counting subtrees, subtree sizes and sums, longest path with constraints, and rerooting where a second top-down pass converts "answer for subtree of v" into "answer for the whole tree rooted at v" for every v in O(n) total.
Complexity is O(n · k) for k flag values, i.e. linear. Constraints are typically n ≤ 10^5–2·10^5, which means recursion depth can be a problem (a path-shaped tree is n deep): use an iterative post-order or raise the stack limit.
Intuition
A mental model before the formal terms.
Every node runs a tiny company and reports to its parent. A report is a fixed-size summary — "best profit if I am hired, best if I am not" — and a parent only needs its children's reports, never their internal details. Reports flow upward once; the root's report is the answer.
For diameter: each node asks "what is the longest chain hanging below me?" (one number) and, while at it, checks whether joining its two longest child chains through itself beats the global best. The global best is the diameter.
How it works
- State:
dp[v][s]— optimal value for the subtree ofvgivenv's own statuss. Choosesto be whatever a parent must know about its child to make its own decision. - Transition:
dp[v][s] = f(v, s) + Σ over children c of g(dp[c][*], s), e.g.take[v] = w[v] + Σ skip[c],skip[v] = Σ max(take[c], skip[c])for maximum independent set. - Base cases: leaves —
take[leaf] = w[leaf],skip[leaf] = 0. With the sum-over-children formulation leaves need no special case. - Order: post-order DFS from the root (children first). Iterative version: obtain a DFS order, then process it in reverse. Answer: combine at the root, or a global best updated at every node for path-type problems.
- Rerooting (optional): after the bottom-up pass, do a top-down pass passing "the contribution of everything outside v's subtree" from parent to child; this yields per-root answers in
O(n).
Why it works
Subtrees of different children are disjoint and interact only through the parent, so given the parent's status the children's choices are independent. Optimal substructure holds and the transition simply sums/maximizes independent optima.
Post-order guarantees every child value is final before the parent reads it; each edge is used O(1) times, hence linear time.
Recognition
How to tell a problem wants this.
- Input is a tree (n nodes, n−1 edges, connected) or a binary tree, and the question is about selecting nodes, longest paths, subtree aggregates, or "for every node compute…".
- Constraints like "no two adjacent chosen nodes", "path through the tree", "distance sums from each node".
- A DFS that returns one or two numbers per node is the natural first attempt.
Interactive visualization
Play, step, change the input. ← → and space work too.
| node | weight | take | skip |
|---|---|---|---|
| n3 | 4 | — | — |
| n4 | 8 | — | — |
| n1 | 5 | — | — |
| n5 | 3 | — | — |
| n6 | 7 | — | — |
| n2 | 12 | — | — |
| n0 | 10 | — | — |
1solve(u): # postorder — children resolve first2 for each child c of u: solve(c)3 take[u] = value[u] + Σ_c skip[c] # u is in the set → no child may be4 skip[u] = Σ_c max(take[c], skip[c]) # u is out → each child picks its own best5answer = max(take[root], skip[root])6reconstruct: walk down, taking u only when take[u] wins and u is still allowedPseudocode
1# maximum-weight independent set on a tree (House Robber III generalized)2dfs(v, parent):3 take = w[v]; skip = 04 for c in adj[v] if c != parent:5 (t, s) = dfs(c, v)6 take += s # if v is taken, children must be skipped7 skip += max(t, s) # if v is skipped, children are free8 return (take, skip)9answer = max(dfs(root, -1))Implementations
1# Tree DP: the state is a subtree, and a node's answer is a fold over its2# children's answers. The natural order is post-order, because a node needs3# every child finished first. Representative example: maximum weight4# independent set on a tree, plus subtree sizes and the tree diameter.5 6 71 · Two values per node: best with the node taken, and best without8def rob_tree_rec(children: list[list[int]], weight: list[int], u: int) -> tuple[int, int]:9 take, skip = weight[u], 010 for v in children[u]:11 ctake, cskip = rob_tree_rec(children, weight, v)12 take += cskip # taking u forbids taking any child13 skip += max(ctake, cskip) # skipping u frees each child to choose14 return take, skip15 16 172 · Iterative post-order, so a deep tree cannot hit the recursion limit18def max_weight_independent_set(children: list[list[int]], weight: list[int], root: int) -> int:19 n = len(children)20 take = [0] * n21 skip = [0] * n22 stack = [[root, 0]] # [node, next child index]23 while stack:24 f = stack[-1]25 u, i = f[0], f[1]26 if i < len(children[u]):27 f[1] += 128 stack.append([children[u][i], 0])29 else:303 · Every child is final, so fold them into this node31 take[u] = weight[u]32 skip[u] = 033 for v in children[u]:34 take[u] += skip[v]35 skip[u] += max(take[v], skip[v])36 stack.pop()37 return max(take[root], skip[root])38 39 40# Shared helper: pre-order list, whose reverse is a valid post-order41def pre_order(children: list[list[int]], root: int) -> list[int]:42 order = []43 stack = [root]44 while stack:45 u = stack.pop()46 order.append(u)47 stack.extend(children[u])48 return order49 50 514 · Subtree sizes: the same post-order fold with a different combiner52def subtree_sizes(children: list[list[int]], root: int) -> list[int]:53 size = [1] * len(children)54 for u in reversed(pre_order(children, root)):55 for v in children[u]:56 size[u] += size[v]57 return size58 59 605 · Diameter: the longest path through each node is its two deepest branches61def tree_diameter(children: list[list[int]], root: int) -> int:62 depth = [0] * len(children)63 best = 064 for u in reversed(pre_order(children, root)):65 d1 = d2 = 0 # two deepest child depths66 for v in children[u]:67 d = depth[v] + 168 if d > d1:69 d1, d2 = d, d170 elif d > d2:71 d2 = d72 depth[u] = d173 best = max(best, d1 + d2)74 return beststack.extend(children[u])pushes all children in one call, which is faster than a loop ofappend.for u in reversed(pre_order(children, root))iterates the fold order without building a second list —reversed()returns an iterator.d1, d2 = d, d1updates both deepest depths in one tuple assignment, which is exactly the shift the two-branch update needs.- The iterative independent-set version uses mutable list frames so
f[1] += 1advances the cursor. take, skip = weight[u], 0in the recursive version initialises both in one statement.
The recursive version hits RecursionError at about 1000 nodes deep, which is why the iterative one is the production form.
reversed()on a list returns a lazy iterator;list[::-1]would copy.stack.extend(iterable)is a single C-level call and beats a Python loop ofappend.sys.setrecursionlimitcan raise the cap but risks a C-stack segfault; the iterative form is the safe answer.d1, d2 = d, d1is the tuple-assignment shift — the other three languages need two statements and a temporary ordering.
- Using the recursive version on a deep tree and hitting
RecursionError. - Writing
d1 = dthend2 = d1, which sets both to the same value. - Using a tuple for the iterative frame and hitting
TypeErroron the cursor increment.
- Recursion depth is the practical driver: CPython raises
RecursionErrornear 1000 frames and JS engines near 10000, so the iterative form is mandatory in both; C++ merely overflows silently, which is worse. - The two-deepest-children shift is one statement in Python (
d1, d2 = d, d1) and needs careful ordering in the other three. - Reverse iteration without copying: C++
rbegin()/rend(), Pythonreversed(), and a backward index loop in JS/TS —reverse()there would mutate. - Pushing many children at once is a single call in Python (
stack.extend) and a loop everywhere else.
Complexity
Rerooting adds a second O(n) pass. Deep trees may need an iterative DFS.
Compare growth rates in the Complexity Explorer →When to use — and when not to
- Optimizing or counting over node selections / paths in a tree.
- "For every node as root" questions — rerooting.
- Tree-shaped dependency structures in general (expression trees, hierarchies).
- The graph has cycles — it is not a tree; DP on general graphs needs DP on DAGs (if acyclic) or a different approach.
- The query is a simple traversal or aggregate (Breadth-First Search (BFS)/Depth-First Search (DFS) suffice) with no optimization component.
- The per-node state would be large (a set of chosen descendants) — reformulate; tree DP works because the state is tiny.
Alternatives
Common mistakes
- Revisiting the parent in an undirected adjacency list (forgetting the
c != parentcheck) — infinite recursion. - Recursion depth overflow on path-like trees with
n = 10^5; use an explicit stack or a reverse-DFS-order loop. - For diameter/path problems, returning the path length instead of the "single chain" length to the parent — parents can only extend one arm.
- Mixing "answer for subtree" with "global answer": path problems need a global best updated at every node.
Interview patterns
- House Robber III / maximum independent set; minimum vertex cover on a tree.
- Diameter of a Binary Tree, Binary Tree Maximum Path Sum, Longest Univalue Path.
- Count nodes / subtree sums; Sum of Distances in Tree (rerooting).
- Tree colouring / painting with adjacency constraints (
dp[v][colour]).
- Choosing between BFS, DFS, Dijkstra and DPAdvanced
- Stack versus queueBeginner
- Recursion versus iterationIntermediate
- When space complexity mattersIntermediate
- Course ScheduleIntermediate
- Number of IslandsIntermediate
- Coin ChangeIntermediate
Example problems
Check yourself
Answer out loud or on paper first, then compare. These come from the interview questions linked to this lesson.
How do you decide between BFS, DFS, Dijkstra, and Dynamic Programming?
Show a strong answerHide the answer
A strong candidate reframes the question: each of these answers a specific question about a specific kind of graph. What am I being asked — reachability, a shortest path, an ordering, an optimal value — and what does the graph look like — weighted or not, cyclic or not, explicit or implicit (states in a puzzle are a graph too).
Breadth-First Search (BFS) answers "fewest edges" and explores by distance layers; it is optimal only when every edge costs the same. Depth-First Search (DFS) answers structural questions — does a path exist, are there cycles, what is a topological order, which components exist — and is the natural backbone of backtracking. Dijkstra's Algorithm is BFS generalized to non-negative weights: replace the queue with a Priority Queue and you are done; its correctness argument breaks the moment a negative edge appears. Dynamic Programming is shortest (or best) path on a DAG: the subproblem dependency graph must be acyclic so subproblems can be solved in one topological pass.
The unifying view: all four are "process states in a valid order and relax transitions". BFS orders by hop count, Dijkstra by tentative distance, DP by topological order of subproblems, DFS by discovery. If the state graph has cycles and weights, you cannot use DP and need Dijkstra; if it is acyclic, DP is simpler and linear; if weights are uniform, BFS is both simpler and faster than Dijkstra.
Full interview question, with follow-ups and red flags →What is the difference between a stack and a queue, and how do you decide which one a problem needs?
Show a strong answerHide the answer
Both hold pending work; they differ only in which item comes out next. A Stack returns the most recently added item (LIFO), a Queue returns the oldest (FIFO). The consequence is bigger than the definition: a stack processes things in nested order — the innermost open thing finishes first — while a queue processes things in arrival order.
Stack signals: matching brackets, undo, expression evaluation, "most recent unmatched element", recursion elimination, and anything where the answer for the current element depends on the nearest previous element with some property (Monotonic Stack). Queue signals: level-by-level processing, "shortest number of steps", scheduling in arrival order, and Breadth-First Search (BFS).
A strong candidate also mentions the Deque as the generalization that supports both ends, used for sliding-window maximum and 0-1 BFS, and notes that swapping the stack for a queue in a graph traversal turns DFS into BFS with no other change.
Full interview question, with follow-ups and red flags →Edge weights are only 0 and 1. What changes?
Show a strong answerHide the answer
0-1 BFS with a deque: push 0-cost neighbours to the front, 1-cost to the back.
Full interview question, with follow-ups and red flags →O(V + E)instead of Dijkstra's log factor.