Lesson 10 · Advanced structures and algorithms

Lowest Common Ancestor

The lowest common ancestor of two nodes is the deepest node that has both of them below it. One post-order pass finds it in any binary tree; a BST needs only one path; binary lifting answers many queries fast.

Lowest Common Ancestor concept diagramA visual explanation of the layout and operations shown in this lesson.the deepest node with both targets somewhere below it35162targettarget5 hears from BOTHsides, so 5 is the LCA
1

What the LCA Is

An ancestor of a node is any node on the path from the root down to it, including the node itself. The lowest common ancestor of p and q is the deepest node that is an ancestor of both: the point where the root-to-p and root-to-q paths split.

Because a node counts as its own ancestor, if q is inside p's subtree the answer is p, not p's parent. In the tree used below, the LCA of 6 and 4 is 5, the LCA of 5 and 4 is 5, and the LCA of 6 and 8 is the root 3.

The LCA always exists in a rooted tree, since the root is an ancestor of everything, and it is unique, since the shared ancestors form one chain from the root.

Its main use is distance. The path between two nodes in a tree must pass through their LCA, so dist(p, q) = depth(p) + depth(q) − 2 · depth(lca). For 6 and 4 that is 2 + 3 − 2 · 1 = 3 edges.

2

The Recursive Method

  1. If the node is null, return null
  2. If the node is p or q, return it; there is no need to look deeper
  3. Otherwise recurse into the left and right children
  4. If both calls return a node, p and q are on different sides: this node is the LCA
  5. If only one returns a node, pass that result up; if neither does, return null

With no ordering to use, a plain binary tree needs a full post-order search. Each call reports what it found in its subtree: a target, the answer, or nothing. The first node to hear back from both sides is where the two paths split, and every node above it just passes that answer up.

The ancestor case needs no extra code. For LCA(5, 4), the search reaches 5 first and returns it without looking at 5's children. Nothing else is found, so 5 travels up to the root and is the answer, which is correct because 4 is below 5.

That shortcut is also the method's weak spot. If q is not in the tree at all, the search still returns p, a wrong answer that looks right. When both nodes are not guaranteed, count the targets actually found, or check membership first.

Every node is visited at most once, so the time is O(n), and the recursion uses O(h) stack, where h is the height. On a tree that is a long chain, h is n and a deep recursion can overflow the stack.

3

LCA in a Binary Search Tree

In a binary search tree the values say which way to go, so the search becomes a single walk down. At each node: if p and q are both smaller, go left; if both are larger, go right; otherwise they split here, or one of them is this node, and this node is the LCA.

That costs O(h) time and, written as a loop, O(1) space. On a balanced BST that is O(log n) instead of O(n). The ancestor case again works on its own: at p, the values do not lie on one side, so p is returned.

Key reference

Terms, operations, and practical uses

Core Concepts

  • AncestorAny node on the direct path from the root to the target node, including the target node itself.
  • Common AncestorA node that serves as an ancestor for both target node P and target node Q.
  • Lowest Common AncestorThe deepest possible common ancestor; the exact point where the paths to P and Q diverge.

Standard Binary Tree

  • Post-order ApproachRecursively search left and right. If both return a non-null target, the current node is the LCA.
  • Single Target ReturnIf only one side finds a target, pass it up. This assumes both P and Q are in the tree; otherwise it returns the one it found.
  • Path RecordingAn alternative O(N) space method is to record the path from root to P and root to Q, then find the last matching node.

Optimizations

  • BST LCAIn a BST, walk down from the root; the first node whose value lies between P and Q, inclusive, is the LCA.
  • Parent PointersWith parent links, lift the deeper node to the same depth, then climb both together until they meet: O(h) time, O(1) space.
  • Binary LiftingPrecomputing a jump table in O(N log N) to answer millions of LCA queries on a static tree in O(log N) time per query.
Implementation

Code in Python, C++ and Java

class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right

def lca(root, p, q):
    if not root or root == p or root == q:
        return root
    left = lca(root.left, p, q)
    right = lca(root.right, p, q)
    if left and right:
        return root
    return left if left else right

n = {v: TreeNode(v) for v in [3, 5, 1, 6, 2, 0, 8, 7, 4]}
n[3].left, n[3].right = n[5], n[1]
n[5].left, n[5].right = n[6], n[2]
n[1].left, n[1].right = n[0], n[8]
n[2].left, n[2].right = n[7], n[4]
for p, q in [(6, 4), (5, 4), (6, 8)]:
    print(f"LCA({p}, {q}) =", lca(n[3], n[p], n[q]).val)
#include <iostream>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left, *right;
    TreeNode(int x, TreeNode* l = nullptr, TreeNode* r = nullptr) : val(x), left(l), right(r) {}
};

TreeNode* lca(TreeNode* root, TreeNode* p, TreeNode* q) {
    if (!root || root == p || root == q) return root;
    TreeNode* left = lca(root->left, p, q);
    TreeNode* right = lca(root->right, p, q);
    if (left && right) return root;
    return left ? left : right;
}

int main() {
    TreeNode* n[9];
    for (int v : {3, 5, 1, 6, 2, 0, 8, 7, 4}) n[v] = new TreeNode(v);
    n[3]->left = n[5]; n[3]->right = n[1];
    n[5]->left = n[6]; n[5]->right = n[2];
    n[1]->left = n[0]; n[1]->right = n[8];
    n[2]->left = n[7]; n[2]->right = n[4];
    int queries[3][2] = {{6, 4}, {5, 4}, {6, 8}};
    for (auto& qr : queries)
        cout << "LCA(" << qr[0] << ", " << qr[1] << ") = " << lca(n[3], n[qr[0]], n[qr[1]])->val << '\n';
}
public class Main {
    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int x) { val = x; }
    }

    static TreeNode lca(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == p || root == q) return root;
        TreeNode left = lca(root.left, p, q);
        TreeNode right = lca(root.right, p, q);
        if (left != null && right != null) return root;
        return left != null ? left : right;
    }

    public static void main(String[] args) {
        TreeNode[] n = new TreeNode[9];
        for (int v : new int[]{3, 5, 1, 6, 2, 0, 8, 7, 4}) n[v] = new TreeNode(v);
        n[3].left = n[5]; n[3].right = n[1];
        n[5].left = n[6]; n[5].right = n[2];
        n[1].left = n[0]; n[1].right = n[8];
        n[2].left = n[7]; n[2].right = n[4];
        int[][] queries = {{6, 4}, {5, 4}, {6, 8}};
        for (int[] qr : queries)
            System.out.println("LCA(" + qr[0] + ", " + qr[1] + ") = " + lca(n[3], n[qr[0]], n[qr[1]]).val);
    }
}
Watch it run

Step through it

Running on LCA(6, 4), LCA(5, 4), LCA(6, 8)

LCA(6, 4): p = 6, q = 401234q56p78callslca(3)waitinglca(5)waitinglca(6)runninggo down until a target or a null child
Step 1

Start at the root

lca(3) is neither target, so it asks its left child, and lca(5) is not a target either, so it asks its left child too. Nothing is decided on the way down: every answer is built from what the children report back.

Output
1 / 15
4

With Parent Pointers

If every node stores its parent, no search from the root is needed. Compute both depths by climbing to the root, move the deeper node up until the depths match, then move both up one step at a time until they meet. The meeting node is the LCA.

That is O(h) time and O(1) extra space. A simpler version stores all of p's ancestors in a hash set and climbs from q until it hits one, at the cost of O(h) space. The depth-matching version is the same trick used to find where two linked lists merge.

  • Climbing one parent at a time is the slow part; binary lifting below makes each climb take O(log n) jumps
5

Binary Lifting for Many Queries

  1. One DFS records each node's depth and parent: up[0][v]
  2. Build up[k][v] = up[k − 1][up[k − 1][v]], the ancestor 2^k levels up, for every k up to log n
  3. Query: lift the deeper node by the depth difference, one jump per 1-bit of that number
  4. If the two nodes are now equal, that node is the LCA
  5. Otherwise, for k from high to low, jump both by 2^k only if their ancestors there differ; the answer is then up[0][p]

When thousands of queries hit the same fixed tree, paying O(n) per query is too slow. Binary lifting stores, for every node, its ancestors 1, 2, 4, 8 … levels up. The table takes O(n log n) time and space, and each query takes O(log n).

The last stage is the part people get wrong. Both nodes jump only when their ancestors at that height are different, so they always stay strictly below the LCA. Jumping when the ancestors are equal could overshoot to a common ancestor that is not the lowest one. When the loop ends, the two nodes are children of the LCA, so one parent step gives the answer.

The same table answers the kth ancestor of a node directly: write k in binary and take one jump per 1-bit. The 5th ancestor is a jump of 4 and then a jump of 1.

A second fast method flattens the tree with an Euler tour, which lists nodes in the order a DFS enters and returns to them. The LCA of p and q is the shallowest node between their positions in that list, a range minimum query that a sparse table answers in O(1) after O(n log n) preprocessing.

LCA methods compared (n nodes, height h)
MethodPreprocessPer queryExtra spaceNeeds
Recursive searchnoneO(n)O(h) stackany binary tree
BST walknoneO(h)O(1)BST ordering
Parent pointersnoneO(h)O(1)parent links
Binary liftingO(n log n)O(log n)O(n log n)a fixed tree
Euler tour + sparse tableO(n log n)O(1)O(n log n)a fixed tree
  • For a node with no ancestor 2^k up, point up[k][v] at the root so jumps never fall off the tree
  • Binary lifting works on any rooted tree, not only binary trees