Sub topic 1
From Unrooted Graph to Rooted Tree
Most tree problems arrive as a list of edges. The input does not name a root, does not mark parents, and does not mention subtrees. Tree DP needs all three. Before you can write a state such as "the best answer inside the subtree of u", you need to decide what the subtree of u is. This chapter turns an unrooted edge list into a rooted tree. It covers the arrays that describe the rooted tree, how they change with the choice of root, and the input mistakes that most often break tree code.
Prerequisites
This chapter assumes you are comfortable with:
- Basic dynamic programming on arrays: states, transitions, and base cases.
- Graph representation with adjacency lists.
- Depth-first search and breadth-first search.
- Big-O complexity analysis.
- Reading Python code, including
collections.deque.
You do not need any prior tree DP. The next chapter covers post-order processing and iterative DFS in detail. This chapter only builds the rooted structure those traversals work on.
What Makes a Graph a Tree
A tree is a connected, undirected graph with no cycles. For a graph with n nodes, the following statements are equivalent, and each one implies the others:
- The graph is connected and has no cycles.
- The graph is connected and has exactly
n - 1edges. - The graph has no cycles and has exactly
n - 1edges. - Every pair of nodes is joined by exactly one simple path.
Statement 4 explains why trees suit dynamic programming. Because there is only one path between any two nodes, removing a single edge splits the tree into exactly two pieces, and nothing connects them except that edge. Information from one piece can reach the other only through that edge. Tree DP relies on this: the answer for a piece can be computed on its own and passed across the cut edge as a small summary.
Statement 2 gives a cheap validity check. Count the edges, then confirm that a traversal from any node reaches all n nodes. If both checks pass, the input is a tree. Self-loops and duplicate edges are also ruled out, because each one uses up an edge without connecting anything new, so the remaining edges cannot connect all n nodes.
Rooting: Parents, Children, and Subtrees
To root a tree, pick any node r as the root. Every edge then gets a direction: it points away from the root. The vocabulary follows from that:
- The parent of a node
vother than the root is the neighbor ofvon its unique path tor. The root has no parent. - The children of
uare the neighbors ofuwhose parent isu. - The depth of
vis the number of edges on the path fromrtov. The root has depth 0. - A leaf is a non-root node with no children.
- The subtree of
uisutogether with all nodes whose path to the root passes throughu. Equivalently, it isuplus the subtrees of its children.
The recursive definition of a subtree is where tree DP starts. If subtree(u) = {u} ∪ subtree(c1) ∪ subtree(c2) ∪ ... and the child subtrees are disjoint, then any quantity that can be built from its parts, such as a size, a sum, or a best choice, can be computed for u from the values already computed for its children.
Here is the running example used throughout this chapter: seven nodes with edges (0,1), (0,2), (1,3), (1,4), (2,5), (5,6), rooted at node 0.
With root 0, the subtree of node 2 is {2, 5, 6}, the subtree of node 1 is {1, 3, 4}, and the leaves are 3, 4, and 6.
Building the Rooted Structure in Code
The usual representation is a set of plain arrays indexed by node:
| Array | Meaning | Value at the root |
|---|---|---|
| `parent[v]` | The parent of `v` | `-1` |
| `depth[v]` | Edges from the root to `v` | `0` |
| `children[u]` | List of the children of `u` | All neighbors of the root |
| `order` | Every node, each parent listed before its children | Starts with the root |
The order array matters more than it looks. Any order in which every parent comes before its children (a "top-down" order) can be reversed to get an order in which every child comes before its parent (a "bottom-up" order). Bottom-up is exactly what tree DP needs. Breadth-first search produces a top-down order naturally, because a node is appended only after its parent has been dequeued.
from collections import deque
def build_adjacency(n, edges):
if len(edges) != n - 1:
raise ValueError(f"a tree on {n} nodes needs {n - 1} edges, got {len(edges)}")
adj = [[] for _ in range(n)]
for u, v in edges:
if not (0 <= u < n and 0 <= v < n):
raise ValueError(f"edge ({u}, {v}) has a node outside 0..{n - 1}")
adj[u].append(v)
adj[v].append(u)
return adj
def root_tree_bfs(n, edges, root=0):
adj = build_adjacency(n, edges)
parent = [-1] * n
depth = [0] * n
children = [[] for _ in range(n)]
seen = [False] * n
seen[root] = True
order = [root]
queue = deque([root])
while queue:
u = queue.popleft()
for v in adj[u]:
if not seen[v]:
seen[v] = True
parent[v] = u
depth[v] = depth[u] + 1
children[u].append(v)
order.append(v)
queue.append(v)
if len(order) != n:
raise ValueError("graph is not connected, so it is not a tree")
return parent, depth, children, order
if __name__ == "__main__":
n = 7
edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (5, 6)]
parent, depth, children, order = root_tree_bfs(n, edges, root=0)
print("parent ", parent)
print("depth ", depth)
print("children", children)
print("order ", order)Running it prints:
parent [-1, 0, 0, 1, 1, 2, 5]
depth [0, 1, 1, 2, 2, 2, 3]
children [[1, 2], [3, 4], [5], [], [], [6], []]
order [0, 1, 2, 3, 4, 5, 6]Each node is enqueued once and each adjacency entry is scanned once, so rooting takes O(n) time and O(n) memory. Because the loop never recurses, a path-shaped tree with a million nodes is no problem.
Why `seen` and not `parent`
A common shortcut skips the seen array and tests if v != parent[u] instead. On a valid tree that works, because the parent is the only already-visited neighbor. On bad input it fails silently: with a duplicate edge (1, 3) listed twice, node 3 is pushed twice and gets processed twice, and with a cycle the traversal never ends. The seen array costs n booleans and makes the traversal terminate on any input. The connectivity check at the end then reports the problem.
The Root Is Your Choice, and It Changes the Subtrees
For most tree DP problems the final answer does not depend on which node you root at. The diameter, the maximum independent set, and the number of valid colorings are all properties of the unrooted tree. The intermediate subtrees, however, depend entirely on the root. Re-root the example at node 5:
Calling root_tree_bfs(7, edges, root=5) returns parent = [2, 0, 5, 1, 1, -1, 5] and order = [5, 2, 6, 0, 1, 3, 4]. Compare the subtrees:
| Node | Subtree with root 0 | Subtree with root 5 |
|---|---|---|
| 0 | all 7 nodes | `{0, 1, 3, 4}` |
| 1 | `{1, 3, 4}` | `{1, 3, 4}` |
| 2 | `{2, 5, 6}` | `{0, 1, 2, 3, 4}` |
| 5 | `{5, 6}` | all 7 nodes |
| 6 | `{6}` | `{6}` |
Node 1's subtree is the same under both roots because the path between 0 and 5 does not pass through any node below 1. Nodes on the path between the two roots (0, 2, 5) are the ones whose subtrees change. In general, the subtree of u is "the side of u facing away from the root", so it changes only when the root moves to a different side of u.
Rooting therefore picks one of many possible views of the tree. Usually one view is enough, and node 0 is a fine default. When a problem asks for an answer per root, such as the sum of distances from every node, recomputing for each root costs O(n²). The rerooting chapter later in this tutorial shows how to move the root across one edge in O(1) and get all n answers in O(n).
Input Formats You Will Meet
Edge lists are the most common format, but not the only one. The table shows how to reach the arrays above from each format.
| Input format | Example | What to do |
|---|---|---|
| Edge list, 0-indexed | `n=4`, edges `0 1`, `1 2`, `1 3` | Use `root_tree_bfs` directly |
| Edge list, 1-indexed | edges `1 2`, `2 3`, `2 4` | Subtract 1 from each endpoint while reading |
| Parent array | `p[1..n-1]`, with `p[i]` the parent of `i` | Already rooted at 0; build edges `(p[i], i)` or use `p` as `parent` |
| Parent array with `p[i] < i` | Common in contest inputs | `order = list(range(n))` is already top-down |
| Weighted edges | `u v w` | Store `(neighbor, w)` pairs; record `parent_weight[v] = w` when rooting |
The "parent array with p[i] < i" case is worth knowing. Every parent has a smaller index than its child, so iterating i from n - 1 down to 1 already processes children before parents, and you need no traversal at all.
Here is the weighted variant, which also stores the weight of the edge to each node's parent. Path-sum and distance problems need that weight.
from collections import deque
def root_weighted_tree(n, weighted_edges, root=0):
adj = [[] for _ in range(n)]
for u, v, w in weighted_edges:
adj[u].append((v, w))
adj[v].append((u, w))
parent = [-1] * n
parent_weight = [0] * n
dist = [0] * n
seen = [False] * n
seen[root] = True
order = [root]
queue = deque([root])
while queue:
u = queue.popleft()
for v, w in adj[u]:
if not seen[v]:
seen[v] = True
parent[v] = u
parent_weight[v] = w
dist[v] = dist[u] + w
order.append(v)
queue.append(v)
return parent, parent_weight, dist, order
if __name__ == "__main__":
edges = [(0, 1, 4), (0, 2, 1), (2, 3, 7)]
parent, pw, dist, order = root_weighted_tree(4, edges)
print(parent, pw, dist, order)
# [-1, 0, 0, 2] [0, 4, 1, 7] [0, 4, 1, 8] [0, 1, 2, 3]Common Errors
These errors account for most wrong answers in rooting code:
- Adding only one direction of each edge. If you append
vtoadj[u]but notutoadj[v], the traversal from the root misses every node whose edge was listed "pointing upward." The connectivity check catches this. Without the check, the result is silently wrong. - Mixing 1-indexed input with 0-indexed arrays. Node
noverflows the array, or node 0 becomes a phantom isolated node. Convert once at input time and nowhere else. - Forgetting the single-node tree. With
n = 1and no edges, the root is also the only node,order = [0], and many DP formulas must still return a sensible value. Test this case explicitly. - Treating the root as a leaf. In a star rooted at a leaf, the real center has
n - 2children and the root has exactly one. Code that defines a leaf as "degree 1" instead of "no children" will misclassify the root. - Assuming DFS and BFS orders are interchangeable for every purpose. Both are top-down, so both can be reversed for bottom-up DP. Only DFS pre-order keeps each subtree contiguous, which matters for techniques that store subtrees as index ranges.
Checking Your Rooting
A quick self-test catches most bugs before you add DP logic on top:
def check_rooting(n, parent, depth, order, root):
assert len(order) == n and sorted(order) == list(range(n))
assert order[0] == root and parent[root] == -1
position = [0] * n
for i, u in enumerate(order):
position[u] = i
for v in range(n):
if v != root:
p = parent[v]
assert position[p] < position[v], "parent must come before child"
assert depth[v] == depth[p] + 1
return TrueRun it after root_tree_bfs on random trees and on edge cases: a path, a star, and n = 1. Once it passes, the reversed order is a valid bottom-up schedule for every DP in the rest of the tutorial.
Exercise
A tree has n = 5 and edges (3, 0), (3, 1), (1, 2), (1, 4). Root it at node 0 with roottreebfs. Give parent, depth, and order, and list the nodes in the subtree of node 3.
Show answer
Adjacency: 0:[3], 1:[3,2,4], 2:[1], 3:[0,1], 4:[1]. BFS from 0 visits 3, then 1, then 2 and 4. parent = [-1, 3, 1, 0, 1], depth = [0, 2, 3, 1, 3], order = [0, 3, 1, 2, 4]. The subtree of node 3 is {3, 1, 2, 4}: every node except the root.
Exercise
An input has n = 4 and edges (0, 1), (1, 2), (2, 0). It has 3 edges, not n - 1 = 3... wait, n - 1 = 3, so the edge count check passes. Explain which check in roottreebfs rejects it, and why the seen array matters here.
Show answer
The graph has a cycle 0-1-2 and node 3 is isolated, so it is not a tree even though it has n - 1 edges. BFS from 0 reaches only 0, 1, and 2, so len(order) is 3, not 4, and the connectivity check raises an error. The seen array guarantees each node is enqueued once, so the cycle cannot make BFS loop forever or add node 2 twice. With a v != parent[u] test instead, node 2 would be reached from both 0 and 1 and appended twice.
Exercise
Under root 0 in the seven-node example, node 2's subtree is {2, 5, 6}. Without running code, state node 2's subtree when the tree is rooted at node 6, and explain the general rule you used.
Show answer
With root 6, the path from 6 to every node other than 5 and 6 passes through 5 and then 2. So node 2's subtree is {2, 0, 1, 3, 4}. The rule: the subtree of u is u plus all components left after deleting u, except the component containing the root. The root 6 lies in the component {5, 6}, so that one is excluded.