1. Walk from root
Descend the BST without recursion.
let node = rootTyporithm · medium
Step 1 of 8 · intro card
Trees
Walk down the BST; the first node where the two targets diverge (one each side, or one equals it) is the LCA.
In a BST, the lowest common ancestor is the node where the search paths to the two targets split.
If both targets are smaller, go left; if both are larger, go right.
The moment they no longer agree on direction, the current node is the answer.
Both smaller → go left.
Both larger → go right.
Otherwise the split node is the LCA.
function lowestCommonAncestor(root, p, q) {
let node = root;
while (node !== null) {
if (p.val < node.val && q.val < node.val) {
node = node.left;
} else if (p.val > node.val && q.val > node.val) {
node = node.right;
} else {
return node;
}
}
return null;
}Connect each part of the code to the concept before you type.
Descend the BST without recursion.
let node = rootIf both targets are smaller, the LCA is in the left subtree.
if (p.val < node.val && q.val < node.val)If both are larger, go right.
else if (p.val > node.val && q.val > node.val)The first node that splits the two targets is their LCA.
return nodeRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.