Sub topic 1
From Unrooted Graph to Rooted Tree
Tree problems usually arrive as an edge list with no direction. Dynamic programming on trees needs a direction. You pick a root, give every node a parent, and solve each subtree from the answers of its children.
Prerequisites
This chapter assumes you know:
- basic dynamic programming on arrays (states, transitions, base cases)
- adjacency lists
- depth-first search
- Big-O analysis
- how to read Python
Rooting the Tree
A tree with n nodes has n - 1 edges, is connected, and has no cycles. Pick any node as the root. Every other node then has exactly one parent, which is its neighbor on the path toward the root. The subtree of u is u plus all nodes below it.
Children Before Parents
Your DP needs every child finished before its parent. Recursive DFS does this, but Python's default recursion limit is about 1000, and a path-shaped tree with 10^5 nodes will crash it. An iterative DFS with a stack avoids the problem. A node gets appended to order before any of its children, so reading order in reverse handles children before parents.
def root_tree(n, edges, root=0):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
parent = [-1] * n
seen = [False] * n
seen[root] = True
order = []
stack = [root]
while stack:
u = stack.pop()
order.append(u)
for v in adj[u]:
if not seen[v]:
seen[v] = True
parent[v] = u
stack.append(v)
size = [1] * n
for u in reversed(order):
if parent[u] != -1:
size[parent[u]] += size[u]
return parent, order, size
print(root_tree(5, [(0, 1), (0, 2), (1, 3), (1, 4)]))
# ([-1, 0, 0, 1, 1], [0, 2, 1, 4, 3], [5, 3, 1, 1, 1])What a Subtree Should Remember
A state is the smallest summary of a subtree that lets the parent finish its own work. To design one, ask what the parent needs to know about the child.
| Problem | State per node |
|---|---|
| Subtree size | node count |
| Independent set | best value with u taken, and best with u skipped |
| Diameter | longest downward path from u |
A common mistake is a state that holds too little. For example, "best independent set value" on its own fails, because the parent also needs to know whether the child itself was chosen.
Exercise
Why does reversing order guarantee that each child is processed before its parent?
Show answer
A node is appended to order only after its parent has been popped and appended. So every parent comes before its children in order, and in the reversed order every child comes before its parent.