Lowest Common Ancestor (LCA)
Lowest Common Ancestor (LCA) finds the deepest node that is an ancestor of two given nodes in a tree. This fundamental tree query operation has applications in computational biology (phylogenetic trees), version control systems (finding merge base), network routing, and range queries. Multiple algorithms exist: simple recursive O(n), binary lifting O(log n) per query after O(n log n) preprocessing, and Tarjan's offline algorithm for batch queries.
Visualization
Interactive visualization for Lowest Common Ancestor (LCA)
Sample Tree Structure:
3
/ \
5 1
/ \ / \
6 2 0 8
/ \
7 4Available nodes: 0, 1, 2, 3, 4, 5, 6, 7, 8
How LCA Works:
- • Recursive approach: traverse left and right subtrees
- • If current node is p or q, return it
- • If both left and right return non-null, current node is LCA
- • Otherwise, return the non-null child result
- • Time Complexity: O(n) - visit each node once
- • Space Complexity: O(h) - recursion stack (h = tree height)
Interactive visualization with step-by-step execution
Implementation
1// Simple approach for binary tree
2function lowestCommonAncestor(root: TreeNode | null, p: TreeNode, q: TreeNode): TreeNode | null {
3 if (!root || root === p || root === q) return root;
4
5 const left = lowestCommonAncestor(root.left, p, q);
6 const right = lowestCommonAncestor(root.right, p, q);
7
8 if (left && right) return root;
9 return left || right;
10}
11
12// With path tracking
13function lowestCommonAncestorPath(root: TreeNode | null, p: TreeNode, q: TreeNode): TreeNode | null {
14 const pathP: TreeNode[] = [];
15 const pathQ: TreeNode[] = [];
16
17 findPath(root, p, pathP);
18 findPath(root, q, pathQ);
19
20 let i = 0;
21 while (i < pathP.length && i < pathQ.length && pathP[i] === pathQ[i]) {
22 i++;
23 }
24
25 return pathP[i - 1];
26}
27
28function findPath(root: TreeNode | null, target: TreeNode, path: TreeNode[]): boolean {
29 if (!root) return false;
30
31 path.push(root);
32
33 if (root === target) return true;
34
35 if (findPath(root.left, target, path) || findPath(root.right, target, path)) {
36 return true;
37 }
38
39 path.pop();
40 return false;
41}Deep Dive
Theoretical Foundation
LCA for binary trees uses elegant recursion: if root is null or matches either node, return root. Recursively search left and right subtrees. If both return non-null (one node in each subtree), root is LCA. If only one returns non-null, LCA is in that subtree. For general trees or online queries, binary lifting preprocesses ancestors at powers of 2: ancestor[node][i] = 2^i-th ancestor. Query brings nodes to same level, then binary searches upward. Time: O(n log n) preprocessing, O(log n) per query. Euler tour + RMQ gives O(n) preprocessing, O(1) per query.
Complexity
Time
O(n)
O(n)
O(n)
Space
O(h) recursion
Applications
Use Cases
Related Algorithms
AVL Tree (Self-Balancing BST)
A self-balancing binary search tree where the heights of the two child subtrees of any node differ by at most one. Named after inventors Adelson-Velsky and Landis (1962), AVL trees guarantee O(log n) time for search, insert, and delete operations by maintaining balance through rotations. It was the first self-balancing binary search tree to be invented.
Segment Tree (Range Query Tree)
Segment Tree is a binary tree data structure for storing intervals/segments that enables efficient range queries (sum, min, max, GCD) and updates in O(log n) time. Each node represents an interval, with leaves representing single elements. Essential for competitive programming, it solves problems like range sum queries with updates, which would be O(n) with arrays but becomes O(log n) with segment trees.
Fenwick Tree (Binary Indexed Tree - BIT)
A data structure that can efficiently update elements and calculate prefix sums in O(log n) time. Also known as Binary Indexed Tree (BIT), invented by Peter Fenwick in 1994. Fenwick trees are more space-efficient and simpler than segment trees for range sum queries, using only O(n) space compared to segment tree's O(4n).
Morris Traversal (Threaded Binary Tree)
Morris Traversal is a brilliant tree traversal technique that achieves O(1) space complexity without using recursion or an explicit stack. Invented by Joseph H. Morris in 1979, it temporarily modifies the tree structure by creating 'threads' (temporary links) that allow the algorithm to traverse back to ancestors. After traversal, the original tree structure is restored. This makes it ideal for memory-constrained environments and demonstrates creative problem-solving in algorithm design.