Tree DFS (Paths & Recursion)
O(n)
Recurse down carrying state (running sum / depth); combine children's results on the way back up.
0/52 solved
Recognise it
The signal
Root-to-leaf paths, path sums, LCA, or a value computed from children: height, diameter, balance, max path sum.
1Brute force
Recompute subtree properties from scratch at every node: O(n2).
2The observation
Recomputation: each subtree's answer is returned once to its parent.
3Why it works
Each call returns the correct summary of its subtree (bottom-up) or receives the correct summary of its root path (top-down).
Reach for it when
- +Root-to-leaf paths, path sums, or 'does a path with property X exist'.
- +A property defined recursively over subtrees — height, diameter, balanced, max path sum, LCA.
- +You want O(height) memory rather than O(width).
Not when
- ×Strict level-by-level outputuse Tree BFS
- ×Shortest path by edge countuse BFS, stops without exploring the whole tree
- ×Multiple interacting choices per node (take/skip, colourings)use Tree DP
- ×Answer needed for every node as rootuse Rerooting
- ×Many path queriesuse Binary lifting or HLD
Intuition
DFS = depth-first: go as deep as you can down one branch before backing up — like exploring a cave, following a tunnel to its dead end, then returning to the last fork. On a tree this is just recursion: "solve the left subtree, solve the right subtree, combine."
Read the full intuition
Two directions of information flow, and naming them fixes most tree confusion:
- Top-down (pass info down): carry state into the call as arguments — a running path sum, the current depth. Decide at the leaf.
- Bottom-up (return info up): each call returns a fact about its subtree (its height, its max path sum), and the parent combines the children's returns. This is the powerful one.
The bottom-up frame is a workhorse:
def dfs(node):
if not node: return base # empty subtree
L = dfs(node.left)
R = dfs(node.right)
return combine(node, L, R) # build this node's answer from children'sWorked example — height: empty → 0; otherwise 1 + max(height(left), height(right)). Diameter reuses the exact same recursion: while returning each node's height, also update a global best with left_height + right_height (the longest path bending at this node). One traversal, two facts — that "compute X but track Y on the side" move solves a whole class of hard tree problems.
Why it costs what it costs
Time O(n). each node is visited once and does O(1) combine work.
Space O(h). recursion stack equals the tree height — O(log n) balanced, O(n) worst case (a chain).
Practice
- Maximum Depth of Binary TreeFoundationFoundationAmazon, MetaEasy
- Same TreeApply it · Recurse on two trees in lockstep.Apply itAmazon, MetaEasy
- Path SumApply it · Pass state top-down.Apply itAmazon, AdobeEasy
- Path Sum IIOne change · Collect paths.One changeAmazon, AdobeMedium
- Count Good Nodes in Binary TreeOne change · State is the max so far on the path.One changeMeta, AmazonMedium
- Balanced Binary TreeTwists · Need height AND validity together.TwistsAmazon, MetaEasy
- Diameter of Binary TreeBranches · Answer passes through a node but the return value is a single arm.BranchesMeta, AmazonEasy
- Lowest Common Ancestor of a Binary TreeBranches · Return found-node signals.BranchesMeta, AmazonMedium
- Path Sum IIICombine · Paths start anywhere going down.CombineMedium
- Binary Tree Maximum Path SumMastery checkMastery checkMeta, AmazonHard
- Invert Binary TreeGoogle, AmazonEasy
- Subtree of Another TreeMeta, AmazonEasy
Pitfalls
Classic bugs
- !Mixing top-down and bottom-up in one function: decide to carry state down or return facts up.
- !Empty-node base case must return the right identity (0 for sums/heights; clamp negatives where needed).
- !Max path sum/diameter: return the extendable single downward path, record the bent path in
best. Don't return the global answer. - !Updating
bestwithoutnonlocal/closure capture loses the update. - !Skewed trees overflow recursion (Python limit ~1000); raise the limit or use an explicit stack.
Looks like it, isn't
- Minimum Height Trees needs Topological Sort
Why
Trying every root is O(n2); peeling leaves (Kahn on degree 1) finds centres.
Go deepervariants and techniques · 20 combinations · resources
Variants and techniques
- DP on Treesdp[v][state] computed from children's dp values in post-order (e.g. take/skip v, cover state, matched or not).
- Binary Lifting & LCAPrecompute up[k][v] = 2^k-th ancestor (or successor) so k-th ancestor, LCA, and path aggregates take O(log n).
- Euler Tour / Tree FlatteningRecord entry/exit times in DFS so each subtree becomes a contiguous range, turning subtree queries into array range queries.
- Small-to-Large Merging (DSU on tree)When merging sets, always insert the smaller into the larger; each element moves O(log n) times, giving O(n log n) (times the set cost).
- Centroid DecompositionRecursively remove a centroid (largest remaining part <= n/2) so every path passes through some centroid at one of O(log n) levels.
- Heavy-Light DecompositionSplit the tree into heavy chains so any path crosses O(log n) chains, then answer path queries with a segment tree over chain order.
- Top-down pathCarry a running sum/path as arguments; act at leaves. Path Sum, Path Sum II.
- Bottom-up propertyReturn a subtree fact (height/validity) and combine. Maximum Depth, Balanced Tree.
- Compute-and-trackReturn one value, update a global best for the 'bending' answer. Diameter, Binary Tree Maximum Path Sum.
- LCAReturn the node if found in a subtree; the split point where both sides return non-null is the LCA. Lowest Common Ancestor.
Combinations
Tree DFS (Paths & Recursion)+Prefix Sum+Hash Map / Hash Set Lookup
count downward paths with a given sum
- Tree DFS (Paths & Recursion):
- walks root-to-node paths
- Prefix Sum:
- path sums as prefix differences
- Hash Map / Hash Set Lookup:
- counts prefix values on the current path
Tree DFS (Paths & Recursion)+Graph BFS / DFS
nodes at distance k from a target node; infection time from a node
- Tree DFS (Paths & Recursion):
- records parent pointers
- Graph BFS / DFS:
- BFS from the target over an undirected view
All Nodes Distance K in Binary TreeAmount of Time for Binary Tree to Be Infected
Binary Lifting & LCA+Tree DFS (Paths & Recursion)
distance between two nodes, k-th ancestor, many queries
- Binary Lifting & LCA:
- jumps to ancestors in O(log n)
- Tree DFS (Paths & Recursion):
- computes depth and parent
Euler Tour / Tree Flattening+Segment Tree / Fenwick (BIT)
subtree sum with value updates; root-to-node path sums
- Euler Tour / Tree Flattening:
- flattens subtrees into ranges
- Segment Tree / Fenwick (BIT):
- range sums with point updates
Heavy-Light Decomposition+Segment Tree / Fenwick (BIT)
max/sum on path u-v with point updates
- Heavy-Light Decomposition:
- maps each path to O(log n) contiguous ranges
- Segment Tree / Fenwick (BIT):
- range max/sum per chain
Small-to-Large Merging (DSU on tree)+Tree DFS (Paths & Recursion)
distinct colours per subtree; dominant colour sums
- Small-to-Large Merging (DSU on tree):
- merges child sets keeping the largest
- Tree DFS (Paths & Recursion):
- post-order over subtrees
Rerooting DP (all roots)+DP on Trees
sum of distances from every node; best value when each node is the root
- Rerooting DP (all roots):
- propagates outside-subtree info to children
- DP on Trees:
- computes answers for subtrees from one root
Centroid Decomposition+Graph BFS / DFS
count paths of length k; nearest marked vertex queries
- Centroid Decomposition:
- splits paths by their top centroid
- Graph BFS / DFS:
- BFS/DFS collects depths from each centroid
Functional / Successor Graphs+Binary Lifting & LCA
teleporters/successor after k steps; first time reaching b from a
- Functional / Successor Graphs:
- every node has one successor
- Binary Lifting & LCA:
- k-step successor in O(log k)
Euler Tour / Tree Flattening+Sparse Table (static RMQ)
many LCA/distance queries on a static tree where O(log n) per query is too slow or you want O(1)
- Euler Tour / Tree Flattening:
- write the 2n-1 vertex visit sequence with depths
- Sparse Table (static RMQ):
- RMQ on depths gives the LCA in O(1)
Virtual (Auxiliary) Tree+DP on Trees+Binary Lifting & LCA
many queries with a small vertex set each and sum of k bounded
- Virtual (Auxiliary) Tree:
- shrink the tree to the O(k) marked vertices and their LCAs
- DP on Trees:
- run the separation/cover DP on the small tree
- Binary Lifting & LCA:
- LCA queries while building the virtual tree
Kruskal Reconstruction Tree+Binary Lifting & LCA
the minimum possible maximum edge between u and v (or the first time they connect) for many pairs
- Kruskal Reconstruction Tree:
- turns each union into a node valued by the edge weight
- Binary Lifting & LCA:
- LCA queries, or jumping to the highest ancestor with value <= x
Kruskal Reconstruction Tree+Euler Tour / Tree Flattening+Segment Tree / Fenwick (BIT)
edges deleted over time, plus queries for the max value in v's current component
- Kruskal Reconstruction Tree:
- the threshold-reachable set is a subtree
- Euler Tour / Tree Flattening:
- that subtree is a contiguous leaf range
- Segment Tree / Fenwick (BIT):
- range max with point delete over the leaf order
Mo's Algorithm (offline range queries)+Euler Tour / Tree Flattening+Hash Map / Hash Set Lookup
many offline path queries counting pairs/distinct values on tree paths
- Mo's Algorithm (offline range queries):
- path = range with odd-toggle membership plus the LCA
- Euler Tour / Tree Flattening:
- a 2n entry/exit sequence
- Hash Map / Hash Set Lookup:
- frequency counts by value or gender pair
DP on Trees+Combinatorics mod p (nCr, Catalan, stars and bars)
count the orders in which tree nodes can be added parent-first (or BST insert orders)
- DP on Trees:
- subtree sizes and the ways for each child
- Combinatorics mod p (nCr, Catalan, stars and bars):
- interleave the children's orders with multinomials, i.e. n! / product of subtree sizes
Count Ways to Build Rooms in an Ant ColonyNumber of Ways to Reorder Array to Get Same BST
Binary (XOR) Trie+Tree DFS (Paths & Recursion)+Offline Query Processing
max XOR of a value with any ancestor of a node, many queries
- Binary (XOR) Trie:
- the max XOR against values on the root path (counts per trie node allow removal)
- Tree DFS (Paths & Recursion):
- on entry insert the node's value, on exit remove it
- Offline Query Processing:
- attach the queries to their nodes
Binary Lifting & LCA+Interval Scheduling (sort by end)
many queries: how many non-overlapping intervals fit inside [a, b]
- Binary Lifting & LCA:
- jump 2^k greedy steps at once
- Interval Scheduling (sort by end):
- from time t, the greedy next movie is the one ending earliest among those starting >= t
Binary Lifting & LCA+Monotonic Stack
count elements of the 'next greater' chain starting at a that lie within b
- Binary Lifting & LCA:
- count how many next-greater jumps stay within [a, b]
- Monotonic Stack:
- next greater element for every index
Block-Cut Tree / Bridge Tree+Binary Lifting & LCA
queries: can a reach b without visiting c (undirected)
- Block-Cut Tree / Bridge Tree:
- turns 'must pass through c' into a tree-path membership test
- Binary Lifting & LCA:
- LCA / ancestor checks for the path test
Probability & Expected-Value DP (linearity of expectation)+Tree DFS (Paths & Recursion)
probability that a random walk on a tree is at vertex v at time t
- Probability & Expected-Value DP (linearity of expectation):
- the probability multiplies by 1/(#unvisited children) at each step
- Tree DFS (Paths & Recursion):
- walk from the root with depth/time