Lowest Common Ancestor of a BST
Given a binary search tree and two nodes p and q that exist in it, return their lowest common ancestor: the deepest node that has both p and q as descendants (a node can be a descendant of itself).
Open official problem prompt ↗Locate the deepest node whose value sits between (or equals) the two target values, using only comparisons.
Two people descend a family tree of sorted account numbers; they walk together as long as both belong on the same side, and part ways at the ancestor that splits them.
- Input
- root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
- Output
- 6
- Why
- 2 lies in the left subtree of 6 and 8 lies in its right subtree, so 6 is the deepest node covering both.
The number of nodes is in the range [2, 10^5]-10^9 <= Node.val <= 10^9All Node.val are uniquep != q and both exist in the BST