😎풀이

  1. 이진 트리 특성 상, 내 우측에 있는 노드는 나보다 큰 값을 갖고 좌측에 있는 노드는 나보다 작은 값을 갖음
  2. low보다 더 작은 값을 갖는 노드는 우측으로 재귀 탐색하며 더 큰 값이 나올 경우 해당 노드를 반환함
  3. high보다 더 큰 값을 갖는 노드는 좌측으로 재귀 탐색하며 더 작은 값이 나올 경우 해당 노드를 반환함
  4. 정돈된 root 노드를 반환함
function trimBST(root: TreeNode | null, low: number, high: number): TreeNode | null {
    if(!root) return null
    if(root.val < low) return trimBST(root.right, low, high)
    if(root.val > high) return trimBST(root.left, low, high)
    root.left = trimBST(root.left, low, high)
    root.right = trimBST(root.right, low, high)
    return root
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글