Lowest Common Ancestor of a BST

Find the lowest common ancestor in a BST.

Pattern

BST Property

This problem follows the BST Property pattern, commonly found in the Trees category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

If both nodes < current, go left. If both > current, go right. Otherwise, current is LCA.

Key Insight

The BST property means the LCA is the first node where p and q 'split' to different subtrees — no need to search both sides.

Step-by-step

  1. 1Start at the root of the BST
  2. 2If both p and q are less than root, go left
  3. 3If both p and q are greater than root, go right
  4. 4Otherwise, root is the LCA (the split point)

Pseudocode

def lowestCommonAncestor(root, p, q):
    while root:
        if p.val < root.val and q.val < root.val:
            root = root.left
        elif p.val > root.val and q.val > root.val:
            root = root.right
        else:
            return root
Complexity Analysis

Time Complexity

O(h)

Space Complexity

O(1)
More Trees Problems

Master this pattern with YeetCode

Practice Lowest Common Ancestor of a BST and similar Trees problems with flashcards. Build pattern recognition through active recall.

Practice this problem