Skip to main content
29

Lowest Common Ancestor of a Binary Search Tree

Mediumtreesbst

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:TreesRead the beginner guide

Given a binary search tree and two of its nodes p and q, return their lowest common ancestor (LCA).

Understand the problem

  • A binary search tree (BST) is a binary tree with an ordering rule: every value in a node's left subtree is smaller than the node, and every value in its right subtree is larger. (The beginner guide covers this.)
  • An ancestor of a node is any node on the path from the root down to it: its parent, its parent's parent, and so on. A node also counts as its own ancestor.
  • A common ancestor of p and q is a node that is an ancestor of both. The root always is.
  • The lowest common ancestor is the deepest one: the point where the paths from the root to p and to q split apart.
text
        6
      /   \
     2     8
    / \   / \
   0   4 7   9
      / \
     3   5

Example 1

text
Input:  p = 2, q = 8
Output: 6

2 is on the left of 6, and 8 is on the right. The paths split at 6.

Example 2

text
Input:  p = 2, q = 4
Output: 2

4 is below 2, and 2 counts as its own ancestor, so the answer is 2 itself.

Example 3

text
Input:  p = 3, q = 5
Output: 4

Both are children of 4.

How the tests work: trees are written level by level with null for a missing child. The tests give p and q as values; your function receives the actual nodes, and the node you return is checked by its value.

Constraints

  • 2 <= number of nodes <= 10^5
  • All values are unique, and p and q both exist in the tree.

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Walk down from the root, going left while both values are smaller and right while both are larger; the first node where they split up is the answer.

    The naive approach (and why it's slow)

    Find the path from the root to p, find the path from the root to q, then compare the two paths and take the last node they share. This works for any binary tree, but it finds two full paths and needs memory to store them. In a BST we can do much better.

    The key insight

    In a BST, the values tell you which way to go. At any node with value v:

    p and q compared with vWhat it meansAction
    both smallerboth live in the left subtree, so their LCA does toogo left
    both largerboth live in the right subtreego right
    one smaller and one larger, or one of them is vthe paths to them split here (or one ends here)this is the LCA

    The split point is the answer because it's the last node on the path to both: one step further and the paths go different ways.

    Step by step

    Using the tree from the description:

    p = 3, q = 5:

    NodeCompareAction
    63 < 6 and 5 < 6go left
    23 > 2 and 5 > 2go right
    43 < 4 but 5 > 4split → 4

    p = 2, q = 4:

    NodeCompareAction
    62 < 6 and 4 < 6go left
    2p is this nodesplit → 2

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(h), where h is the tree's height: we walk one path down. That's O(log n) for a balanced tree.
    • Memory: O(1). Just one pointer, no recursion.

    Common mistakes

    • Searching the whole tree. That ignores the BST ordering, which is the whole point of the problem.
    • Forgetting that a node is its own ancestor. If p is above q, the answer is p. The "otherwise, return" branch handles this automatically.
    • Mixing up < and > in the two conditions. Both must be smaller to go left, both larger to go right.

    Going deeper

    In a plain binary tree (no ordering), the values give no direction, so you search both sides: if the current node is p or q, return it; otherwise recurse left and right, and the node where both sides found something is the LCA. That's O(n) instead of O(h). It's a common follow-up question.

    Reference solution

    js
    /**
     * @param {TreeNode} root
     * @param {TreeNode} p
     * @param {TreeNode} q
     * @return {TreeNode}
     */
    export default function lowestCommonAncestor(root, p, q) {
      let node = root
      while (node) {
        // Both smaller: both live in the left subtree, so their LCA does too.
        if (p.val < node.val && q.val < node.val) node = node.left
        // Both larger: both live in the right subtree.
        else if (p.val > node.val && q.val > node.val) node = node.right
        // They split here (or one of them IS this node): this is the lowest common ancestor.
        else return node
      }
      return null
    }
    ts
    export default function lowestCommonAncestor(
      root: TreeNode | null,
      p: TreeNode,
      q: TreeNode,
    ): TreeNode | null {
      let node = root
      while (node) {
        // Both smaller: both live in the left subtree, so their LCA does too.
        if (p.val < node.val && q.val < node.val) node = node.left
        // Both larger: both live in the right subtree.
        else if (p.val > node.val && q.val > node.val) node = node.right
        // They split here (or one of them IS this node): this is the lowest common ancestor.
        else return node
      }
      return null
    }
    python
    def lowest_common_ancestor(root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
        node = root
        while node:
            # Both smaller: both live in the left subtree, so their LCA does too.
            if p.val < node.val and q.val < node.val:
                node = node.left
            # Both larger: both live in the right subtree.
            elif p.val > node.val and q.val > node.val:
                node = node.right
            # They split here (or one of them IS this node): this is the lowest common ancestor.
            else:
                return node
        return None