Lowest Common Ancestor in a BST
Write the code, see it run, pass the checks.
The problem
- medium
- Code
- Pro
Write lowestCommonAncestor(root, p, q). root is a binary search tree made of nodes { value, left, right }, where left and right are child nodes or null; every value in a node's left subtree is smaller than its own, and every value in its right subtree larger. p and q are two different values in the tree. Return the value of their lowest common ancestor: the deepest node with both values in its subtree, where a node counts as part of its own subtree. For example, in the tree written in level order as [6, 2, 8, 0, 4, 7, 9, null, null, 3, 5], the answer for 3 and 5 is 4, for 2 and 8 it's 6, and for 2 and 4 it's 2.
Your code must pass
- Finds the node where the two values split
- Returns one of the values when it's above the other
- Works whichever order p and q come in
- Works on a deeper, uneven tree