Sub topic 1
From Unrooted Graph to Rooted Tree
Tree DP problems usually give you a tree as a plain list of edges. The edges have no direction, and no node is marked as the top. To run dynamic programming, you first need a structure where every node has one parent and a set of children, so that "the subtree of u" has a clear meaning. This chapter shows how to build that structure.
Prerequisites
This chapter assumes you are comfortable with:
- Basic dynamic programming on arrays: states, transitions, and base cases.
- Storing graphs as adjacency lists.
- Depth-first and breadth-first search.
- Big-O analysis.
- Reading Python code.
What "rooting" means
A tree is a connected, undirected graph with n nodes and exactly n - 1 edges. Any two nodes in a tree are joined by exactly one simple path.
Rooting means choosing one node r as the root and then directing every edge away from it. After rooting:
- The parent of a node
u(other thanr) is the next node on the unique path fromutor. - The children of
uare its neighbors other than its parent. - The subtree of
uisutogether with all of its descendants. - The depth of
uis the number of edges betweenuandr.
The graph stays the same. Rooting only adds labels to it. If you pick a different root, the parents and subtrees change, but the edges do not. Later chapters on rerooting depend on this.
Building parent, depth, and children arrays
The method below uses breadth-first search (BFS) from the root. Each time it first reaches a node, it records the node it came from as that node's parent. The method uses no recursion, so it works on a path of 200,000 nodes, where a recursive DFS would hit Python's default recursion limit of about 1,000.
from collections import deque
def root_tree_bfs(n, edges, root=0):
if len(edges) != n - 1:
raise ValueError("a tree on n nodes has exactly n - 1 edges")
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
parent = [-1] * n
depth = [0] * n
seen = [False] * n
seen[root] = True
queue = deque([root])
visited = 0
while queue:
u = queue.popleft()
visited += 1
for v in adj[u]:
if not seen[v]:
seen[v] = True
parent[v] = u
depth[v] = depth[u] + 1
queue.append(v)
if visited != n:
raise ValueError("graph is not connected")
children = [[] for _ in range(n)]
for v in range(n):
if parent[v] != -1:
children[parent[v]].append(v)
return parent, depth, children
edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5)]
parent, depth, children = root_tree_bfs(6, edges, root=0)
print(parent) # [-1, 0, 0, 1, 1, 2]
print(depth) # [0, 1, 1, 2, 2, 2]
print(children) # [[1, 2], [3, 4], [5], [], [], []]The method visits each node once and looks at each edge twice, so it runs in O(n) time and uses O(n) memory.
You often do not need the children lists. Many DP loops only need parent and a traversal order, and the next chapter builds one. Still, children makes the idea of a subtree concrete while you are learning.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Adding each edge in one direction only | Some nodes are never reached | Append both `v` to `adj[u]` and `u` to `adj[v]` |
| Not tracking visited nodes or the parent | Infinite loop, or a child treated as its own grandparent | Use a `seen` array, or skip `v == parent[u]` |
| Mixing 1-indexed input with 0-indexed arrays | `IndexError` or an off-by-one parent array | Subtract 1 when reading, or allocate `n + 1` slots |
| Recursive DFS on deep trees | `RecursionError` or a crash on path-shaped tests | Use BFS or an explicit stack |
| Assuming the input is a tree | Wrong answers when the input has a cycle or is disconnected | Check the edge count and the visited count |
Which root to choose
For most tree DP problems, any root gives the right answer, so node 0 (or 1) is the usual choice. The root affects which node's subtree covers the whole tree, and it affects the shape of intermediate states. It does not affect the final answer to a problem defined on the whole tree. Some problems fix the root for you, such as "the company hierarchy rooted at the CEO". In those cases, use the given root.
Exercise
Root the example tree (edges (0,1), (0,2), (1,3), (1,4), (2,5)) at node 1 instead. Give the parent array, and list the nodes in the subtree of node 0.
Show answer
parent = [1, -1, 0, 1, 1, 2]. Node 1 is now the root, and its children are 0, 3, and 4. Node 2 hangs under 0, and node 5 hangs under 2. The subtree of 0 is {0, 2, 5}. When the tree was rooted at 0, this subtree was the whole tree.
Exercise
A test case is a path 0-1-2-...-199999 given as 199,999 edges. Why does a recursive DFS rooting function fail in Python while roottreebfs works?
Show answer
Recursive DFS goes one call deeper for each node along the path, so it reaches a depth of about 200,000. That is far above Python's default recursion limit of about 1,000, so the program raises RecursionError, or crashes if you raise the limit. BFS keeps its pending nodes in a deque on the heap, so its memory use grows linearly and the call stack never gets deep.