😎풀이

  1. 좌측과 우측 재귀함수를 실행하여 qp에 해당하는 노드를 탐색
  2. 둘 다 탐색되었다면 현재의 노드가 LCA가 됨
  3. 한 쪽만 탐색되었다면 qp 모두 해당 쪽에 있는 것이므로 해당 노드가 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;
}
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글