Pick any two nodes in a tree — say node 7 and node 11. Their lowest common ancestor (LCA) is the deepest node that is an ancestor of both: the point where their two paths up to the root converge.
LCA is everywhere in practice: it drives distance queries between nodes (the distance from u to v equals ), it underlies compiler control-flow analysis, and it powers database query optimizers working on hierarchical data. The question comes up not once, but in bulk: you have a tree with n nodes and q pairs, and you need all q answers.
The naive approach queries each pair independently. The most basic method — walk up from each node until the paths meet — costs O(depth) per query, which is on a skewed tree. A classic binary lifting table brings each query to , so q queries cost . That is good, but it still grows with both n and q.
Robert Tarjan's offline algorithm (1979) blows past that bound. If you are willing to collect all q queries first and answer them together rather than on-demand (that is, "offline"), a single DFS over the tree — enhanced with a Union-Find structure — resolves every query in total time, where is the inverse Ackermann function, effectively a constant in any realistic setting. For large batches that savings is enormous.
Comments
Loading comments...