In a BST, you can determine which subtree contains each node by comparing values:
def lowestCommonAncestor(root, p, q):
while root:
if p.val < root.val and q.val < root.val:
root = root.left
elif p.val > root.val and q.val > root.val:
root = root.right
else:
return root
return null
If both values are smaller, both nodes are in the left subtree. If both are larger, both are in the right subtree. Otherwise, current node is the split point—the LCA.
Time: . Space: .
Compare this to the general binary tree LCA which is . The BST property lets us find LCA in without checking both subtrees.