Lowest Common Ancestor of a Binary Search Tree

Medium

Topics
TreeDFSBST

Given a binary search tree and two node values p and q present in it, return the value of their lowest common ancestor — the deepest node that has both as descendants (a node can be a descendant of itself).

Example 1

023456789
the two targetslowest common ancestor
Because this is a BST the search never has to branch: at each node, if both targets are smaller go left, if both are larger go right, and otherwise the targets have split and that node is the answer — 6. No parent pointers and no path storage.
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6

Example 2

023456789
the two targetslowest common ancestor
Input:  root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2

Constraints

  • 2 <= number of nodes <= 10^5
  • All node values are unique.
  • p and q exist in the BST.
Editorial — intuition, approach, complexity and pitfalls

Intuition

The BST ordering tells you which way to go. If both p and q are smaller than the current node, the LCA is in the left subtree; if both larger, in the right. The first node that splits them (or equals one) is the LCA.

Approach

  1. Start at the root.
  2. If both p and q are less than node.val, go left; if both greater, go right.
  3. Otherwise the node is the split point — return it.

Dry Run

tree 6 2 8 0 4 7 9 null null 3 5
          6
        /   \
       2     8
      / \   / \
     0   4 7   9
        / \
       3   5
p = 2, q = 8
  at 6: 2 is smaller, 8 is larger -- the targets split here   answer 6
p = 2, q = 4
  at 6: both 2 and 4 are smaller, descend left
  at 2: p IS this node, so it cannot be anywhere below        answer 2
The ordering turns a search into a single descent: no recursion, no parent
pointers, O(h) time and O(1) space. While both targets fall on the same side of
the current node, that side still contains both, so the ancestor must be deeper.
The first node where they do not agree is the split point.
The second case is the subtle one. An ancestor is allowed to BE one of the two
nodes, which is what makes the `else: return node` branch correct rather than a
missing case -- when p equals the current value, neither comparison holds and the
node is returned.
That is also why the comparisons are strict. With <=, a node that is one of the
targets gets stepped past instead of returned: on the tree [-5,-20,5] with
p = -20 and q = -5 the answer is the root, -5, but <= descends left and returns
-20.

Complexity

  • Time — O(h): you descend a single path.
  • Space — O(1): iterative, constant extra space.

Common Pitfalls

  • The comparisons must be strict. With <=, a node that is one of the two targets gets stepped past instead of returned: on the tree [-5,-20,5] with p=-20 and q=-5 the answer is the root -5, but <= descends left and returns -20.
  • An ancestor is allowed to be one of the nodes. That single sentence is what makes the else: return node branch correct rather than a missing case.

Full Solution — all languages

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def lowestCommonAncestor(self, root, p, q):
        node=root
        while node:
            if p<node.val and q<node.val: node=node.left
            elif p>node.val and q>node.val: node=node.right
            else: return node.val
        return -1
Asked at BlackRock LinkedIn
SensAI
Beta
Tap the mic to stop voice mode