Lowest Common Ancestor of a BST: the idea to remember.
Find the lowest common ancestor of two existing nodes in a BST with distinct values.
The core insight
Move left if both values are smaller and right if both are larger; otherwise the current node is the split or one target itself.
Why it works
While both nodes lie on the same side, their lowest common ancestor must also lie there. At the first split, no lower subtree contains both.
The mistake to avoid
A node is allowed to be its own ancestor. If one target equals the current node, stop there.
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while (root != null) {
if (p.val < root.val && q.val < root.val) root = root.left;
else if (p.val > root.val && q.val > root.val) root = root.right;
else return root;
}
return null;
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.