This problem follows the BST Property pattern, commonly found in the Trees category. Recognizing this pattern is key to solving it efficiently in an interview setting.
If both nodes < current, go left. If both > current, go right. Otherwise, current is LCA.
The BST property means the LCA is the first node where p and q 'split' to different subtrees — no need to search both sides.
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 rootPractice Lowest Common Ancestor of a BST and similar Trees problems with flashcards. Build pattern recognition through active recall.
Practice this problem