Given a binary search tree and two of its nodes p and q, return their lowest common ancestor: the deepest node that has both as descendants (a node counts as its own descendant).
Record the search path from the root to p and to q. The LCA is the last node the two paths share. This works for any tree if you swap the BST search for a DFS.
1function lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode): TreeNode {2const path = (target: TreeNode) => {3const out: TreeNode[] = [];4for (let n: TreeNode | null = root; n; n = target.val < n.val ? n.left : n.right) {5out.push(n);6if (n === target) break;7}8return out;9};10const a = path(p), b = path(q);11let i = 0;12while (i < a.length && i < b.length && a[i] === b[i]) i++;13return a[i - 1];14}
Record the root-to-node path for p and for q.
Space: play/pause · ←/→: step