In a BST, the LCA is the first node whose value is between p.val and q.val. If both p and q are smaller than the root, the LCA must be in the left subtree. If both are larger, it's in the right subtree.
- Start at the
root. - While
curris not None:- If
p.valandq.valare both smaller thancurr.val, movecurr = curr.left. - Else if
p.valandq.valare both larger thancurr.val, movecurr = curr.right. - Otherwise,
curris the LCA. returncurr.
- If
- Time Complexity: O(H).
- Space Complexity: O(1).
def lowest_common_ancestor_bst(root, p, q):
curr = root
while curr:
if p.val < curr.val and q.val < curr.val:
curr = curr.left
elif p.val > curr.val and q.val > curr.val:
curr = curr.right
else:
return curr