Lowest Common Ancestor of a Binary Search Tree

Mediumtreebinary-search-treedepth-first-search
Category: Trees
Companies that ask this question:
AmazonFacebookMicrosoftGoogleLinkedIn

Approach

Lowest Common Ancestor of a Binary Search Tree

Problem Statement

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA: "The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself)."

Examples

Example 1

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6

Tree:
        6
       / \
      2   8
     / \ / \
    0  4 7  9
      / \
     3   5

Explanation: LCA of 2 and 8 is 6 (root)

Example 2

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2

Explanation: LCA of 2 and 4 is 2 (node can be ancestor of itself)

Example 3

Input: root = [2,1], p = 2, q = 1
Output: 2

Intuition

The BST property is key: left < root < right

For nodes p and q, the LCA is the split point where:

  • One node is in the left subtree
  • One node is in the right subtree
  • OR current node equals one of them

Key insight: Use BST property to navigate without searching entire tree!

If both p and q are:

  • Less than current node → LCA must be in left subtree
  • Greater than current node → LCA must be in right subtree
  • On different sides (or one equals current) → Current node is LCA

Pattern Recognition

This is a BST Property Exploitation problem with:

  • O(h) solution using BST ordering
  • No need to search entire tree
  • Simple comparison-based navigation

Approach

Iterative (Recommended)

while current:
  if p.val < current.val and q.val < current.val:
    current = current.left   # Both in left subtree
  elif p.val > current.val and q.val > current.val:
    current = current.right  # Both in right subtree
  else:
    return current          # Found split point (LCA)

Why this works:

  • We navigate down the tree using BST property
  • When p and q are on different sides (or one matches current), we've found LCA
  • No need to explore both subtrees

Recursive (Alternative)

def lowestCommonAncestor(root, p, q):
  if p.val < root.val and q.val < root.val:
    return lowestCommonAncestor(root.left, p, q)
  if p.val > root.val and q.val > root.val:
    return lowestCommonAncestor(root.right, p, q)
  return root

Edge Cases

  • One node is ancestor of the other
  • Both nodes are in same subtree
  • Root is the LCA
  • p and q are adjacent nodes
  • Nodes at maximum depth

Complexity Analysis

  • Time: O(h) where h = height of tree

    • Follow one path from root to LCA
    • O(log n) for balanced BST
    • O(n) for skewed BST
    • Much better than O(n) for general tree!
  • Space:

    • Iterative: O(1) - no recursion stack
    • Recursive: O(h) - recursion stack

Solution

java
1class TreeNode {
2    int val;
3    TreeNode left;
4    TreeNode right;
5    TreeNode(int x) { val = x; }
6}
7
8class Solution {
9    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
10        TreeNode current = root;
11
12        while (current != null) {
13            // Both p and q are in left subtree
14            if (p.val < current.val && q.val < current.val) {
15                current = current.left;
16            }
17            // Both p and q are in right subtree
18            else if (p.val > current.val && q.val > current.val) {
19                current = current.right;
20            }
21            // Found the split point (LCA)
22            else {
23                return current;
24            }
25        }
26
27        return null;  // Should never reach here if p and q are in tree
28    }
29}
30
Loading visualizer...