Problem
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.
Example 1
root = [6, 2, 8, 0, 4, 7, 9, null, null, 3, 5]
Example 2
- Input
- p = 2, q = 8
- Output
- 6
Example 3
- Input
- p = 2, q = 4
- Output
- 2
- Why
- 2 is an ancestor of 4, and of itself
Example 4
- Input
- p = 3, q = 5
- Output
- 4
Constraints
2 <= number of nodes <= 10^5-10^9 <= Node.val <= 10^9All values are distinct, p != q, and both exist in the tree.