sagelearnai

Lowest Common Ancestor of a BST

Difficulty: Medium · Pattern: Trees & BST · LeetCode #235

Given a BST and two nodes p and q in it, return their lowest common ancestor: the deepest node that has both p and q as descendants (a node counts as its own descendant).

In the tests, p and q are given by value; your function receives the actual node objects. The expected output shows the LCA's value.

Examples

text
tree = [6, 2, 8, 0, 4, 7, 9, null, null, 3, 5]
p = 2, q = 8   →  6
p = 2, q = 4   →  2     (a node can be its own ancestor)
p = 3, q = 5   →  4

Hints

  1. Use the BST ordering: if both values are smaller than the current node, where must the LCA be?
  2. The LCA is the first node where p and q go to different sides (or one of them is the node).

Approach

Start at the root. If both p and q are smaller, move left; if both are larger, move right; otherwise the current node splits them (or equals one of them), so it's the LCA. Iterative, O(h) time and O(1) space. (For a general binary tree without ordering, see LeetCode 236, which uses a bottom-up DFS.)

Complexity

Time: O(h). Space: O(1).

Python solution
def lowestCommonAncestor(root, p, q):
    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
    return None
JavaScript solution
function lowestCommonAncestor(root, p, q) {
  let node = root;
  while (node) {
    if (p.val < node.val && q.val < node.val) node = node.left;
    else if (p.val > node.val && q.val > node.val) node = node.right;
    else return node;
  }
  return null;
}