Technique
Euler Tour / Tree Flattening
Record entry/exit times in DFS so each subtree becomes a contiguous range, turning subtree queries into array range queries.
0/8 solved
Recognise it
The signal
subtree sum/update queries
1Brute force
DFS the subtree for each query.
2The observation
Per-query DFS: the subtree is the range [tin[v], tout[v]].
3Why it works
u is an ancestor of v iff tin[u] <= tin[v] and tout[v] <= tout[u].
Reach for it when
- +is u an ancestor of v
- +LCA via RMQ on the Euler sequence
Not when
- ×path queries that are not root-to-node (hld)
Practice
- Distance QueriesCSESMedium
- Company Queries IICSESMedium
- Subtree QueriesCSESMedium
- Graph and QueriesCodeforces2600
- DatingCodeforces2300
- Path QueriesCSESHard
- Tree QueriesCodeforces1900
- Tree RequestsCodeforces2200
Pitfalls
Misconceptions
- !mixing the 2n-length Euler sequence (for LCA) with the n-length tin order (for subtrees)
Go deeper4 combinations · resources
Combinations
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
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)
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