Lowest Common Ancestor of a Binary Search Tree, visualized step by step

Medium One of the Blind 75 interview problems (LeetCode 235). Technique: binary search tree walk. Solution in Python, explained at every step.

The problem

You get the root of a binary search tree and two of its nodes, p and q. In a binary search tree, every value in a node's left subtree is smaller than the node's value, and every value in its right subtree is larger. Return the lowest common ancestor of p and q: the lowest node that has both of them in its subtree. A node is part of its own subtree, so the answer can be p or q itself.

Example: 8 is at the root, with 3 and 11 under it, 1 and 6 under 3, and 9 and 14 under 11. For 1 and 6 the answer is 3: the root 8 has both of them below it too, but 3 is lower.

The search tree with p under 1 and q under 6; their lowest common ancestor 3 is green. Answer: 3. The same tree with p under 11 and q under 14; 11 is green. Answer: 11.
In the second picture the answer is p itself: 11 has both 11 and 14 in its subtree.

Try it yourself first: LeetCode 235 ↗. Then step through the solution below.

Brute force

Treat it as any binary tree: search the whole tree for the path from the root to p and for the path to q, then walk both paths from the root until they part. The last node they share is the answer. That is O(n) time, since each search may visit every node, and O(h) space, since a path holds one node per level. It never uses the order of the values.

The key insight

The clue is in the words "binary search tree". At any node, the order of the values says where p and q are without looking: if both are smaller than the node, both are in its left subtree, and so is their lowest common ancestor. If both are larger, all three are in its right subtree.

So walk down from the root, always to the side both are on. The first node where they are not on one side is the answer: one of them is on its left and the other on its right, or the node is one of them. Every node above it has both on one side, and no node below it has both.

Step by step

The player runs the code on the example. Press → for each step: the lines it runs light up in the code.

On a phone, Full screen keeps the picture and the code on one screen.

Lowest Common Ancestor of a Binary Search Tree, step by step

Python

class TreeNode:    def __init__(self, val, left=None, right=None):        self.val, self.left, self.right = val, left, right def lowest_common_ancestor(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
All steps as text
  1. In this search tree, p is 1 and q is 6. Which is the lowest node that has both of them in its subtree?
  2. node starts at the root, 8. The walk goes down from there.
  3. 1 and 6 are both smaller than 8, so both are in 8's left subtree.
  4. Move node to 8's left child, 3. The right subtree, all larger than 8, holds neither.
  5. At 3 they part: 1 is smaller and 6 larger, so neither test holds. They are on different sides.
  6. Return node, 3: the lowest common ancestor. Below it, no node has both 1 and 6 in its subtree.
  7. The walk tested two nodes, one a level: O(h) time for a tree of height h. It keeps one variable: O(1) space.
Lowest Common Ancestor of a Binary Search Tree, step by step. Last step: The walk tested two nodes, one a level: O(h) time for a tree of height h. It keeps one variable: O(1) space.

Complexity

ApproachTimeSpace
Brute force: both paths from the root, comparedO(n)O(h)
The same walk, written recursivelyO(h)O(h)
Walk down to the side both are on this pageO(h)O(1)

n is the number of nodes, and h the height of the tree.

  • Time: O(h). One node per level, from the root down: O(log n) for a balanced tree, O(n) for a tree that is one long chain.
  • Space: O(1). One variable, node, whatever the size of the tree; the loop needs no call stack.

Edge cases

  • One of them is the answer, like p = 11 and q = 14: the walk stops at 11 itself; the walkthrough below steps through it.
  • On both sides of the root, like 1 and 14: the root already splits them, and the walk returns it without moving.
  • p larger than q, like 6 and 1: each test asks about both at once, so the order of the two does not matter: 3 again.
  • A tree that is one long chain, like 1 → 2 → 3 → 4 down the right side, with 3 and 4: the walk tests 1, 2 and 3, a node on every level but the last. That is the O(h) bound at its worst.

When the answer is p itself

The same code on the second example: p is 11 and q is 14, and the answer is p itself. Up to step 2 it runs as before; then both are larger than 8, so the walk goes right. Press → for each step.

Lowest Common Ancestor, when the answer is p itself

Python

class TreeNode:    def __init__(self, val, left=None, right=None):        self.val, self.left, self.right = val, left, right def lowest_common_ancestor(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
All steps as text
  1. In the same tree, p is 11 and q is 14. Which is the lowest node that has both of them in its subtree?
  2. node starts at the root, 8. The walk goes down from there.
  3. 11 and 14 are both larger than 8, so both are in 8's right subtree.
  4. Move node to 8's right child, 11. The left subtree, all smaller than 8, holds neither.
  5. At 11, node is p itself: 11 is not larger than itself, so neither test holds.
  6. Return node, 11: the answer is p itself, since a node is part of its own subtree.
  7. When one of them is the answer, the walk stops there by itself: the code needs no separate check for p or q.
Lowest Common Ancestor of a Binary Search Tree — Lowest Common Ancestor, when the answer is p itself. Last step: When one of them is the answer, the walk stops there by itself: the code needs no separate check for p or q.

Try it: put Lowest Common Ancestor of a Binary Search Tree together step by step

The blocks below are steps of Lowest Common Ancestor of a Binary Search Tree in words, and two of them do not belong. Put the right ones in order and check: your algorithm runs on the example and on the walkthrough "When the answer is p itself", so a mistake shows in its answer. Once it is right, the code appears beside your blocks.

Put Lowest Common Ancestor of a Binary Search Tree together

Click the blocks in the order they run, or drag them into the lines.Tap the blocks in the order they run. Two of them don't belong. Each block keeps its indent: it runs inside the nearest line above it that ends in a colon.

Your algorithm

Blocks

Interview follow-up

What if the tree is not a search tree? That is Lowest Common Ancestor of a Binary Tree (LeetCode 236). A value no longer tells the side, so each call searches both subtrees: it returns its node if that node is p or q, and a node whose two subtrees both found one is the answer. O(n) time, and O(h) space for the calls.

The data structure behind it

  • Binary search tree: search, insert and delete, each a walk down from the root, step by step.