Algorithms · Trees & recursion
Lowest Common Ancestor of a Binary Search Tree
In a search tree, find where two values’ paths split.
The problem
In a binary search tree, everything on a node’s left is smaller and everything on its right is bigger. Return the value of the lowest node that has both p and q underneath it (a node counts as being under itself). Use the ordering!
check([6, 2, 8, 0, 4, 7, 9, None, None, 3, 5], 2, 8)→6check([6, 2, 8, 0, 4, 7, 9, None, None, 3, 5], 2, 4)→2Start with the way that works
This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.
def path_to(root, target):find the way from the top down to target if root is None:fell off the tree return Nonenot down here if root.val == target:found it return [root]the path is just this node for child in (root.left, root.right):otherwise search both sides (ignoring the order) p = path_to(child, target)look down this side if p:found down there? return [root] + padd this node to the front return Nonenot anywhere below def lowest_common(root, p, q):take a tree and two values a, b = path_to(root, p), path_to(root, q)both paths from the top last = Nonethe last node both paths share for x, y in zip(a, b):walk down both paths together if x is not y:they split here breakstop last = xstill the same node return last.valthe lowest shared nodeNow ask: what if there were a billion?
Databases store their indexes as search trees (B-trees) with hundreds of children per node, so finding one row among a billion takes about four steps down the tree.
Aim for O(log n)🔥 boss
Think it through
Both values are smaller than this node. Where is the answer?
- On the left
- Could be either side
Show the answer
On the left. In a search tree everything smaller lives on the left. So both are down there, and so is their lowest shared ancestor.
One value is smaller and one is bigger than this node. What then?
- Keep going left
- This node is the answer
Show the answer
This node is the answer. They split here, so this is the lowest node above both. You walk down one path and never look at the rest: the ordering does the searching.
Stuck? 3 nudges, smallest first
- The obvious way searches the whole tree as if it had no order. But the order tells you which way to go.
- If both values are smaller than this node, the answer must be on the left. Both bigger: on the right.
- Walk down from the top: go left while both are smaller, right while both are bigger, and stop when they split.
The fast way
Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.
Show the fast version
def lowest_common(root, p, q):take a tree and two values node = rootstart at the top while node:walk down if p < node.val and q < node.val:both smaller? node = node.leftthey're both on the left elif p > node.val and q > node.val:both bigger? node = node.rightthey're both on the right else:they split here (or one of them is here) return node.valthis is the lowest common ancestorWhere it’s used for real
Solve it yourself.
It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.