Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithms · Dynamic Programming

Answers Flow Up.

A tree has no cycles, and that’s exactly what makes dynamic programming on it clean: each node’s answer depends only on its children’s answers, so a single post-order pass (children before parents) computes everything. Take the maximum-weight independent set — choose nodes with the largest total weight such that no two chosen nodes are adjacent. The trick is to keep two numbers at each node: the best total if you take it (then its children can’t be taken) and the best if you skip it (each child free to choose). Watch the two values flow up from the leaves and the optimal set light up.

O(n) — one post-order pass · two states per node · no-cycles = clean subproblems
independent set

A set of nodes with no two adjacent. Here we want the maximum total weight.

post-order

Process children before their parent, so a node’s subanswers are ready when needed.

take(v)

Best total for v’s subtree if v is chosen — add v, and all children must be skipped.

skip(v)

Best total for v’s subtree if v is not chosen — each child takes its own best.

tree-dp.js — take it, or skip it
Ready
A weighted tree. We compute, for every node, two values: take (best if we pick it) and skip (best if we don’t). Processing leaves first, each value comes from the children below. Step in post-order.
–
solving node
0/7
nodes done
–
max weight

How it works

The recurrence is short but complete. For a node v with weight w(v) and children c: if you take v, you gain w(v) but must skip every child, so take(v) = w(v) + Σ skip(c). If you skip v, each child is free to do whatever is best for it, so skip(v) = Σ max(take(c), skip(c)). A leaf has take = w and skip = 0. Because a tree has no cycles, these subtree answers never depend on each other circularly — one post-order pass fills them all, and the answer is max(take(root), skip(root)).

1

Start at the leaves

A leaf’s take value is just its own weight; its skip value is 0. Leaves have no children, so their answers are immediate.

2

Take = weight + children skipped

To take a node, add its weight and require every child to be skipped: take(v) = w(v) + Σ skip(c). Adjacent nodes can’t both be chosen.

3

Skip = children choose freely

If a node is skipped, each child independently contributes its better option: skip(v) = Σ max(take(c), skip(c)).

✓

Answer at the root

After the post-order pass reaches the root, the maximum-weight independent set is max(take(root), skip(root)). Trace the choices back down to recover which nodes are in it.

Time
O(n)
States / node
2 (take/skip)
Pass
one post-order
Why easy
no cycles

The code

# max-weight independent set on a tree, O(n) def solve(v, parent): take = w[v] # take v: add its weight skip = 0 # skip v for c in children(v, parent): t, s = solve(c, v) # post-order: child first take += s # if v taken, children skipped skip += max(t, s) # if v skipped, child picks best return take, skip t, s = solve(root, None) answer = max(t, s) # best independent-set weight

Quick check

1. Why keep two values (take and skip) at each node?

2. What is take(v) in terms of the children?

3. Why is dynamic programming on a tree so clean?

FAQ

What is tree DP?

Dynamic programming on tree problems, where each node’s answer is computed from its children in one post-order pass (children before parents). A tree’s lack of cycles means subproblems are subtrees that never depend circularly, so it runs in linear time.

What is a maximum-weight independent set?

An independent set is a set of nodes with no two adjacent; the maximum-weight one has the largest total node weight. NP-hard on general graphs, but linear-time on trees via tree DP with a take/skip value per node.

How do you recover which nodes are in the optimal set?

Store both values, then trace down from the root: pick the larger of take/skip at the root. A taken node forces its children skipped; a skipped node lets each child pick its larger option. Following these decisions marks the optimal set.

What other problems use tree DP?

Subtree sizes/sums, tree diameter, tree colorings, minimum vertex cover and dominating set on trees, counting matchings, facility placement, and rerooting (an answer for every node as root). The pattern: combine children’s results at each node in a post-order pass.

The picture: two numbers per node

0 (w=3)t15 s161 (w=7)t7 s32 (w=8)t8 s93 (w=2)t2 s04 (w=1)t1 s05 (w=4)t4 s06 (w=5)t5 s0t = take, s = skip; answer max(t, s) at the root = 16
The seven-node tree used in the worked example, with weights in brackets and the two values each node reports upward: t (best total in its subtree if this node is taken) and s (best total if it is skipped). The highlighted nodes are the chosen set. The root is skipped even though it has two big subtrees below it, which is why you cannot decide a node by looking at its own weight alone.

Worked example, step by step

Tree edges [0,1] [0,2] [1,3] [1,4] [2,5] [2,6], weights [3, 7, 8, 2, 1, 4, 5] for nodes 0 to 6, rooted at 0. Pick non-adjacent nodes with the largest total. Nodes are processed in post-order, children before parents, with take = w + Σ skip(child) and skip = Σ max(take, skip) over the children.

NodeWeightChildrentakeskipbest
32none202
41none101
173, 47 + 0 + 0 = 72 + 1 = 37
54none404
65none505
285, 68 + 0 + 0 = 84 + 5 = 99
031, 23 + 3 + 9 = 157 + 9 = 1616

Read the last three rows. Node 1 (weight 7) beats its children (2 + 1 = 3), so it takes (take 7, skip 3). Node 2 (weight 8) loses to its children, which are worth 4 + 5 = 9, so it skips (take 8, skip 9). At the root the choice is between take = 3 + 3 + 9 = 15 and skip = 7 + 9 = 16, so the answer is 16, with the root skipped. Tracing back down from the root gives nodes 1, 5, 6, and none of them is adjacent to another. Each node's two numbers were computed once from its children's, which is why the whole tree costs one pass, and it matches the best of all 128 subsets checked by brute force (16).

Complexity and trade-offs

CaseTimeSpaceWhy
Tree DP (take / skip)O(n)O(n)One visit per node; two integers each. The recursion stack adds up to O(height).
Brute force over subsetsO(2ⁿ · n)O(n)Check every subset for adjacent pairs. 2⁷ = 128 subsets here, but 2⁴⁰ is about 1.1 × 10¹².
Greedy: heaviest node firstO(n log n)O(n)Fast but not correct: it is a heuristic, not an algorithm for this problem.
Re-run the DP from every rootO(n²)O(n)Needed only when the answer depends on the root, such as “farthest node from each node”.
Rerooting DPO(n)O(n)Computes the answer for all roots with one down pass and one up pass.

The tree is what makes the problem easy: on a general graph, maximum independent set is NP-hard, and nothing like this table-fill exists. Removing a node splits a tree into independent pieces, so the subtree answers can be combined without looking at each other. The greedy line is worth a concrete number: on the tree above, taking the heaviest node first picks 8 (node 2) then 7 (node 1) and stops at 15, one short of the true 16. The space cost is the part people trip over: the table is tiny, but a recursive implementation on a path-shaped tree of a million nodes needs a million stack frames, so deep inputs call for an explicit order or an iterative traversal.

Common mistakes

  • Letting skipped nodes’ children be skipped too

    Writing skip(v) = Σ skip(child) forbids taking anything below a skipped node. On the tree above the root's two values become take 3 and skip 0, so you return 3 instead of 16. A skipped node frees its children to take or skip: Σ max(take, skip).

  • Returning only take(root)

    The answer is max(take(root), skip(root)). Here take(root) is 15 and skip(root) is 16. A star with centre weight 1 and three leaves of weight 5 shows it more starkly: taking the centre gives 1, skipping it gives 15.

  • Choosing greedily by weight

    Taking the heaviest available node feels right and fails: on the tree above it returns 15, not 16, because the 8 at node 2 blocks two leaves worth 9 together.

  • Walking an undirected edge list without a parent

    An edge [a, b] appears in both adjacency lists. A recursive walk that does not skip the node it came from calls itself forever (or until the stack runs out) on the very first edge. Pass the parent down, or mark visited nodes.

  • Recursing on a deep tree

    A chain of 5000 nodes exceeds Python’s default recursion limit of 1000 and raises RecursionError. Compute a traversal order first, then process it in reverse, so each node is handled after all of its children.

Where this shows up

  • Non-adjacent selection on a tree

    Choosing which nodes to take so that no parent and child are both taken is the maximum-weight independent set, which also appears as “rob houses arranged in a binary tree” and as picking guests so no one attends with their direct manager.

  • Subtree statistics

    Tree diameter, subtree sizes, the number of leaves below each node and the sum of distances all use the same pass: compute each node’s value from its children’s, bottom-up.

  • Covering problems

    Minimum vertex cover and minimum dominating set are hard on general graphs but linear on trees, with a small state per node (for example covered/not covered) in place of take/skip.

  • Probabilistic inference on trees

    Likelihood calculations on a phylogenetic tree combine each node’s children’s values bottom-up in this same way, with a probability vector in place of take/skip.

SOLVE IT YOURSELF

Solve it: the best set of non-adjacent nodes

On a general graph this is NP-hard. On a tree it falls to one post-order pass, because each subtree only has to report two numbers upward. Python or TypeScript.

YOUR TASK

Implement max_independent_set(n, edges, weights): pick a set of nodes with no two adjacent, maximising total weight, and return that weight.

HINTS — 6 IDEAS
  1. Each node reports two answers upward: the best total for its subtree including itself, and the best excluding itself.
  2. include[u] = weight[u] + the sum of exclude[child] — taking u forbids every child.
  3. exclude[u] = the sum of max(include[child], exclude[child]) — skipping u leaves each child free to choose.
  4. Process children before parents. A post-order walk guarantees it; here that is a DFS pushing an order, then reading it in reverse.
  5. The answer is max(include[root], exclude[root]).
  6. Recursion is the obvious way to write this, but a deep path-shaped tree will blow the stack — the reference builds an explicit order instead, which is why the tests include a 1000-node chain.
CPython · WebAssembly

Keep going

Finished this one? 0 / 99 Algorithms done
NextBitmask DP: Sets as Integers Next on the “When the state is not a number” ladder · rung 2 of 4

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms