Trees & BST · Pattern 7 of 12

Lowest common ancestor: in a binary tree and in a BST

Ask both subtrees whether they contain p or q. The first node where the answers come from different sides (or the node is one of them) is the lowest common ancestor.

3 variations · 6 problems · 3 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • The deepest node that has both p and q below it
  • A path between two nodes (it goes up to their LCA and down again)
  • Nodes with parent pointers, or a "region" hierarchy given as lists

The template

LCA
TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if (root == null || root == p || root == q) return root;   // found one, or nothing
    TreeNode l = lowestCommonAncestor(root.left, p, q);
    TreeNode r = lowestCommonAncestor(root.right, p, q);
    if (l != null && r != null) return root;                   // one on each side: this is it
    return l != null ? l : r;                                  // pass up whatever was found
}

// in a BST the values tell you where p and q are: walk down until they split
TreeNode lowestCommonAncestorBST(TreeNode root, TreeNode p, TreeNode q) {
    while (root != null) {
        if (p.val < root.val && q.val < root.val) root = root.left;
        else if (p.val > root.val && q.val > root.val) root = root.right;
        else return root;
    }
    return null;
}

The variations

  1. 1Recursive LCA in a binary tree

    Return the node if it is p or q, otherwise return what the children found. With many target nodes, return the node when it is in the set. For directions, find the LCA, then the path from it to each node.

  2. 2LCA in a BST

    If both values are smaller, go left; if both are bigger, go right; otherwise they split here. O(h) and no recursion needed.

  3. 3With parent pointers

    Walk up from both nodes. Like the intersection of two linked lists: when one pointer reaches the top, restart it at the other node, and they meet at the LCA. Regions are the same with a parent map.

Mistakes to avoid

  • The basic version assumes p and q are both in the tree. If one may be missing, count how many you actually found before trusting the answer.
  • Comparing values instead of nodes in a plain binary tree: values can repeat.
  • Directions between two nodes: the part from the start up to the LCA is all U moves, whatever the turns were.
Next: Child and ancestor handling: the tree as a graph →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.