Given a binary tree and two of its nodes p and q, return their lowest common ancestor: the deepest node that has both p and q as descendants (a node counts as its own descendant).
Return p or q if found in a subtree, else null. If both subtrees return something, this node is the split point: the LCA. Otherwise pass up whichever side found something.
1function lowestCommonAncestor(root: TreeNode | null, p: TreeNode, q: TreeNode): TreeNode | null {2if (!root || root === p || root === q) return root;3const left = lowestCommonAncestor(root.left, p, q);4const right = lowestCommonAncestor(root.right, p, q);5if (left && right) return root;6return left ?? right;7}
At 3: search the left subtree.
Space: play/pause · ←/→: step