← Back to Algorithms, page 3

algorithms-0055 · Medium mid

Lowest common ancestor: given two nodes of a binary tree, find their deepest shared ancestor, and show the faster method when the tree is a BST.

Recurse: if the current node is null or equals p or q, return it. Otherwise search both children; if both return non-null, the current node is the LCA, else pass up whichever side found something. That is O(n) time and O(h) space. In a BST, walk from the root, going left while both values are smaller and right while both are larger; the first split point is the LCA in O(h).

Full answer

Problem

Given the root of a binary tree and two nodes p and q that exist in it, return their lowest common ancestor: the deepest node that has both p and q as descendants. A node counts as a descendant of itself.

Example: in the tree 3 -> (5 -> 6, (2 -> 7, 4)), (1 -> 0, 8), LCA(5, 1) is 3, LCA(5, 4) is 5, and LCA(7, 4) is 2.

Constraints: up to 10^5 nodes, values unique, both nodes present.

Brute force

Find the root-to-p path and the root-to-q path, then walk both from the start and return the last shared node. This is O(n) time but needs O(h) memory for two stored paths and two separate searches.

Optimal approach

One recursive pass:

  1. If root is None, p or q, return root.
  2. left = lca(root.left), right = lca(root.right).
  3. If both are non-null, p and q are in different subtrees, so return root.
  4. Otherwise return the non-null side.

For a BST, use values: while both are smaller than the node go left, while both are larger go right, otherwise return the node.

Why it works

Each call returns p, q, the LCA, or None for its subtree. The first node where p and q come back from different sides is the point where their paths diverge, which is the deepest common ancestor. If one of them is an ancestor of the other, the recursion returns it as soon as it is reached, which is correct because a node is its own descendant. In a BST, the split point is the first node whose value lies between p and q.

Complexity

General tree: O(n) time, O(h) recursion. BST: O(h) time and O(1) extra space with the loop.

Code

python
import random


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


def lca(root, p, q):
    """Lowest common ancestor of nodes p and q in any binary tree. O(n) time, O(h) space."""
    if root is None or root is p or root is q:
        return root
    left, right = lca(root.left, p, q), lca(root.right, p, q)
    if left and right:
        return root                      # p and q are on different sides
    return left or right


def lca_bst(root, p, q):
    """In a BST, walk down: both smaller go left, both larger go right. O(h)."""
    node = root
    while node:
        if p.val < node.val and q.val < node.val:
            node = node.left
        elif p.val > node.val and q.val > node.val:
            node = node.right
        else:
            return node


def brute(root, p, q):
    """Compare root-to-node paths; the last shared node is the LCA."""
    def path(n, target, acc):
        if n is None:
            return None
        acc = acc + [n]
        if n is target:
            return acc
        return path(n.left, target, acc) or path(n.right, target, acc)
    a, b = path(root, p, []), path(root, q, [])
    shared = None
    for x, y in zip(a, b):
        if x is not y:
            break
        shared = x
    return shared


def insert(root, v):
    if root is None:
        return TreeNode(v)
    if v < root.val:
        root.left = insert(root.left, v)
    else:
        root.right = insert(root.right, v)
    return root


def nodes(root):
    return [] if root is None else [root] + nodes(root.left) + nodes(root.right)


if __name__ == "__main__":
    n5, n1, n6, n2, n0, n8, n7, n4 = (TreeNode(v) for v in (5, 1, 6, 2, 0, 8, 7, 4))
    root = TreeNode(3, n5, n1)
    n5.left, n5.right, n1.left, n1.right = n6, n2, n0, n8
    n2.left, n2.right = n7, n4
    assert lca(root, n5, n1) is root
    assert lca(root, n5, n4) is n5                  # a node is its own ancestor
    assert lca(root, n7, n4) is n2
    rng = random.Random(55)
    for _ in range(300):
        bst = None
        for v in rng.sample(range(100), rng.randint(1, 15)):
            bst = insert(bst, v)
        all_nodes = nodes(bst)
        p, q = rng.choice(all_nodes), rng.choice(all_nodes)
        assert lca(bst, p, q) is lca_bst(bst, p, q) is brute(bst, p, q)
    print("all tests passed")

Save as b55_lca.py and run python3 b55_lca.py. It prints all tests passed (Python 3.13.5).

Edge cases

p equals q (returns p). One node is the ancestor of the other. Nodes not present (the basic version assumes presence; to handle absence, count how many were found and return None if fewer than two). Compare nodes by identity when values may repeat.

Pattern

Bottom-up information passing in a tree. Variants include LCA with parent pointers (two-pointer walk like linked-list intersection), many queries on a static tree (binary lifting or Euler tour plus range minimum), and distance between two nodes as depth(p) + depth(q) - 2 * depth(lca).

python
import random


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


def lca(root, p, q):
    """Lowest common ancestor of nodes p and q in any binary tree. O(n) time, O(h) space."""
    if root is None or root is p or root is q:
        return root
    left, right = lca(root.left, p, q), lca(root.right, p, q)
    if left and right:
        return root                      # p and q are on different sides
    return left or right


def lca_bst(root, p, q):
    """In a BST, walk down: both smaller go left, both larger go right. O(h)."""
    node = root
    while node:
        if p.val < node.val and q.val < node.val:
            node = node.left
        elif p.val > node.val and q.val > node.val:
            node = node.right
        else:
            return node


def brute(root, p, q):
    """Compare root-to-node paths; the last shared node is the LCA."""
    def path(n, target, acc):
        if n is None:
            return None
        acc = acc + [n]
        if n is target:
            return acc
        return path(n.left, target, acc) or path(n.right, target, acc)
    a, b = path(root, p, []), path(root, q, [])
    shared = None
    for x, y in zip(a, b):
        if x is not y:
            break
        shared = x
    return shared


def insert(root, v):
    if root is None:
        return TreeNode(v)
    if v < root.val:
        root.left = insert(root.left, v)
    else:
        root.right = insert(root.right, v)
    return root


def nodes(root):
    return [] if root is None else [root] + nodes(root.left) + nodes(root.right)


if __name__ == "__main__":
    n5, n1, n6, n2, n0, n8, n7, n4 = (TreeNode(v) for v in (5, 1, 6, 2, 0, 8, 7, 4))
    root = TreeNode(3, n5, n1)
    n5.left, n5.right, n1.left, n1.right = n6, n2, n0, n8
    n2.left, n2.right = n7, n4
    assert lca(root, n5, n1) is root
    assert lca(root, n5, n4) is n5                  # a node is its own ancestor
    assert lca(root, n7, n4) is n2
    rng = random.Random(55)
    for _ in range(300):
        bst = None
        for v in rng.sample(range(100), rng.randint(1, 15)):
            bst = insert(bst, v)
        all_nodes = nodes(bst)
        p, q = rng.choice(all_nodes), rng.choice(all_nodes)
        assert lca(bst, p, q) is lca_bst(bst, p, q) is brute(bst, p, q)
    print("all tests passed")

General recursive LCA, the BST walk, and a path-comparison brute force; random BSTs cross-check all three.

Complexity

Time: O(n) general, O(h) BST. Space: O(h) general, O(1) BST loop. For many queries on a fixed tree, binary lifting gives O(log n) per query after O(n log n) preprocessing.

By level

Fresher: Explains the path-comparison approach and then the recursive version on the sample tree. Handles the case where one node is an ancestor of the other.

Mid: Writes the single-pass recursion and the BST walk, and states what each call returns. Handles missing nodes by counting how many were found.

Senior: Discusses binary lifting or Euler tour with sparse tables for heavy query loads and the preprocessing cost. Connects LCA to practical uses such as version-control merge bases and shortest paths in hierarchies.

Key points

  • Return p, q, LCA or None from each subtree
  • Both sides non-null means the current node is the split
  • A node is its own ancestor
  • BST: move toward the side containing both values
  • Distance = depth(p) + depth(q) - 2 * depth(lca)

Common mistakes

  • Returning early before checking both sides when it matters for presence checks
  • Comparing by value when values are not unique
  • Using the BST shortcut on a general tree
  • Assuming both nodes exist when the interviewer did not say so

Follow-ups

  • How do you handle the case where one node might be missing?
  • How would you answer a million LCA queries on a fixed tree?
  • What if nodes have parent pointers and the root is unknown?

Tips

  • Clarify presence and uniqueness first
  • Explain what each recursive call returns
  • Mention the BST speed-up if the tree is ordered

Evaluation rubric

  • Correct single-pass recursion
  • Handles ancestor-of-itself case
  • Knows the BST and parent-pointer variants
  • Correct complexity