LeetCode 235 Lowest Common Ancestor of BST - Solution

The core idea

Use the BST property to guide your search.

Starting from the root:

  • If both p and q are smaller than the current node, the LCA is in the left subtree.
  • If both p and q are larger than the current node, the LCA is in the right subtree.
  • Otherwise, the current node is the LCA (one is on the left, one is on the right, or one is the current node).

The BST structure tells you exactly which way to go at each step.