Lowest common ancestor in a BST
Medium TimeO(h) SpaceO(h)
The lowest common ancestor of two nodes is the deepest node with both of them somewhere below it, where a node counts as its own descendant — so one value may be the ancestor of the other. Given a binary search tree obeying its ordering, and two values p and q that are both present in it, return their lowest common ancestor.
Examples
Example 1
- Input
- node = buildTree()p = 1q = 3
- Output
- 1 and 3 are the two children of 2, so 2 is the deepest node with both below it.
2
Example 2
- Input
- node = buildTree()p = 2q = 3
- Output
- 3 is below 2, and a node counts as its own descendant — so the answer is
22itself.
The Code
function buildTree() {
return {
val: 4,
left: { val: 2, left: { val: 1, left: null, right: null }, right: { val: 3, left: null, right: null } },
right: { val: 7, left: { val: 6, left: null, right: null }, right: { val: 9, left: null, right: null } }
};
}
function lowestCommonAncestor(node, p, q) {
if (node === null) return null;
if (p < node.val && q < node.val) return lowestCommonAncestor(node.left, p, q);
if (p > node.val && q > node.val) return lowestCommonAncestor(node.right, p, q);
return node.val;
}
lowestCommonAncestor(buildTree(), 1, 3);Done
More like this
All binary trees examples (9) →- Inorder traversal Left subtree, then the node, then right — a BST comes out sorted.
- Max tree depth A node is one deeper than its deepest child.
- Invert a tree Swap every node’s children, all the way down.
- Validate a BST Every node needs a valid range, not just a valid parent.
- Level order (BFS) Process a whole row, collecting the next one as you go.
- Tree diameter Each node returns a depth upward while quietly recording a width.