q
와 p
에 해당하는 노드를 탐색q
와 p
모두 해당 쪽에 있는 것이므로 해당 노드가 LCA가 됨function lowestCommonAncestor(root: TreeNode | null, p: TreeNode, q: TreeNode): TreeNode | null {
if (!root) return null;
if (root === p || root === q) return root;
const left = lowestCommonAncestor(root.left, p, q);
const right = lowestCommonAncestor(root.right, p, q);
if (left && right) return root;
return left || right;
}