DSA · Pro · Pattern 7 of 9
Advanced Trees (BST, LCA, Tree DP)
16 problems.
Your progress0%
- 1st Visit
- 0/16
- 2nd Visit
- 0/16
- Revise
- 0/16
About this pattern
Tree problems at this level rely on three ideas beyond basic traversal. In a binary search tree, in-order traversal visits keys in sorted order, which makes validation, recovery and deletion systematic. For ancestor and path queries on a rooted tree, binary lifting stores the 2^j-th ancestor of every node and answers k-th ancestor and lowest common ancestor queries in O(log n). Tree DP returns a small tuple from each subtree, such as the best result with and without its root, and rerooting reuses those values to answer the question for every possible root in O(n). Signals: ancestor or path queries, or an answer required for every vertex.
const int LOG = 18, MAXN = 200005;
vector<int> adj[MAXN];
int up[LOG][MAXN], dep[MAXN];
void dfs(int u, int p) { // call dfs(root, root)
up[0][u] = p;
for (int j = 1; j < LOG; j++) up[j][u] = up[j - 1][up[j - 1][u]];
for (int v : adj[u]) if (v != p) { dep[v] = dep[u] + 1; dfs(v, u); }
}
int lca(int a, int b) {
if (dep[a] < dep[b]) swap(a, b);
for (int j = LOG - 1; j >= 0; j--)
if (dep[a] - (1 << j) >= dep[b]) a = up[j][a];
if (a == b) return a;
for (int j = LOG - 1; j >= 0; j--)
if (up[j][a] != up[j][b]) { a = up[j][a]; b = up[j][b]; }
return up[0][a];
}