Skip to main content

Tree Algorithms

Why Trees Matter

Trees appear everywhere in CP: organizational hierarchies, file systems, game trees, and as subproblems in graph algorithms. A tree with n nodes has exactly n-1 edges and a unique path between any two nodes. Analogy: A tree is a family genealogy chart. There is one ancestor at the top (the root), each person has exactly one parent (except the root), and there are no marriages within the family (no cycles). The unique path between any two people goes up to their lowest common ancestor, then down. Key properties to internalize:
  • n nodes, n-1 edges, always connected, no cycles
  • Removing any edge splits the tree into exactly two components
  • Adding any edge creates exactly one cycle
  • The path between any two nodes is unique
Pattern Recognition Signals:
  • “n nodes, n-1 edges” → It’s a tree
  • “Unique path between nodes” → Tree path queries
  • “Subtree sum/count” → DFS + subtree aggregation
  • “Path from u to v” → LCA + path decomposition
  • “Root the tree at node 1” → DFS from root

Tree Representations


DFS on Trees

Basic Template

Euler Tour (Flatten Tree to Array)

Converts tree to array for range queries on subtrees. This is one of the most important techniques in tree problems. The Insight: When you run DFS, you visit each node’s subtree contiguously. If you record the entry time tin[u] and exit time tout[u], then the subtree of u occupies a contiguous range [tin[u], tout[u]) in the Euler order. This means you can answer subtree queries (sum, min, max of values in u’s subtree) using a segment tree or BIT over the flattened array. Visual Example for tree with root 1, children 2 and 3, where 2 has children 4 and 5:
Application: Range queries on subtrees using segment trees. Update a node’s value at position tin[u] in the segment tree, and query subtree sums over [tin[u], tout[u]-1].

Pattern 1: Tree Diameter

Problem: Find the longest path in a tree. The tree diameter is the number of edges on the longest path between any two nodes. Why the double-BFS trick works: Starting from any node, the farthest node from it must be an endpoint of some diameter. This is provable by contradiction: if the farthest node were not a diameter endpoint, there would exist a longer path, contradicting that our node was farthest. So BFS from any start gives one diameter endpoint, and BFS from that endpoint gives the other.

Two BFS/DFS Method

DP Method (Also Returns Path)


Pattern 2: Lowest Common Ancestor (LCA)

Problem: Find the lowest common ancestor of two nodes.

Binary Lifting

Precompute ancestors at powers of 2 for O(log n) queries.
Codeforces Problems:

Pattern 3: Tree DP

Subtree DP

Problem: Compute something for each subtree.

Rerooting DP

Problem: Compute answer for each node as if it were the root. A naive approach would run a separate DFS for each root—O(n^2) total. Rerooting DP does it in O(n) with two DFS passes. The Trick: First compute the answer for one root (say node 1) using a standard DFS. Then, in a second DFS, “re-root” the tree to each child by adjusting the parent’s answer. When we move the root from u to its child v, the distances to nodes in v’s subtree decrease by 1 each, while distances to all other nodes increase by 1 each.

Pattern 4: Centroid Decomposition

Problem: Efficiently answer path queries on trees. The centroid is a node whose removal leaves no subtree larger than n/2. Every tree has at least one centroid, and at most two. Analogy: The centroid is the “center of gravity” of the tree. If you tried to balance the tree on a single node like a mobile, the centroid is where it balances — no side is too heavy. Why it works for path queries: After finding the centroid and removing it, the tree splits into subtrees of size at most n/2. We solve for all paths through the centroid, then recursively solve each subtree. Since subtrees are at most half the size, there are at most O(log n) levels of recursion, giving O(n log n) total work for many problems. When to use: Path queries that involve counting or aggregation (paths of length k, closest pair in tree, etc.) where direct LCA-based solutions would be too slow.

Pattern 5: Small-to-Large Merging

Problem: Aggregate information from children efficiently.
Complexity: O(n log² n) total due to small-to-large merging.

Pattern 6: Tree Isomorphism

Problem: Check if two trees have the same structure.

Common Mistakes

Mistake 1: Forgetting parent check in DFS
Mistake 2: Wrong Euler tour indices Subtree of u is [tin[u], tout[u]), not [tin[u], tout[u]].
Mistake 3: LCA on unprocessed tree Always call preprocess(root) before LCA queries.

Practice Problems

Beginner (1000-1300)

Intermediate (1300-1600)

Advanced (1600-1900)


Key Takeaways

Euler Tour

Flattens tree to array for range queries on subtrees.

Binary Lifting

O(log n) LCA queries after O(n log n) preprocessing.

Rerooting DP

Compute answer for all roots in O(n) total.

Small-to-Large

Merge smaller sets into larger for O(n log² n).

Next Up

Chapter 16: Disjoint Set Union

Master Union-Find for dynamic connectivity and Kruskal’s MST.