Lowest Common Ancestor in a BST
MediumTrees
Decode it first. Clues, constraints, pattern and plan before any code.Given the root of a binary search tree and two values p and q that both exist in it, return the value of their lowest common ancestor: the deepest node that has both p and q in its subtree. A node counts as being in its own subtree.
Trees in the examples are written in level order (top to bottom, left to right), with null for a missing child, the same way the tests build them.
root = [6, 2, 8, 0, 4, 7, 9, null, null, 3, 5]
p = 2, q = 8 → 6
p = 2, q = 4 → 2 (2 is an ancestor of 4, and of itself)
p = 3, q = 5 → 4Constraints
2 <= number of nodes <= 10^5-10^9 <= Node.val <= 10^9- All values are distinct,
p != q, and both exist in the tree.