😎풀이

  1. 이진 트리 특성 상 해당 노드보다 좌측노드들은 항상 더 낮은 수, 우측 노드들은 항상 더 큰 수임
  2. root의 값이 p와 q보다 크다면, 우측 노드들은 탐색할 필요 없음
  3. root의 값이 p와 q보다 작다면, 좌측 노드들은 탐색할 필요 없음
  4. 해당 조건들에 부합하지 않는다면 root는 p와 q의 최소 공통 조상임
function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null {
	if(!root) return null
    if(root.val > p.val && root.val > q.val && root.left) return lowestCommonAncestor(root.left, p, q)
    if(root.val < p.val && root.val < q.val && root.right) return lowestCommonAncestor(root.right, p, q)
    return root
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글