😎풀이

  1. nums 요소가 있는 경우, 최댓값을 기준으로 좌우측 요소는 각각 트리를 기준으로 재귀적 생성
  2. nums 요소가 없는 경우, null을 반환하여 무한 루프 방지
function constructMaximumBinaryTree(nums: number[]): TreeNode | null {
    if(nums.length > 0) {
        const max = Math.max(...nums)
        const maxIdx = nums.indexOf(max)
        const left = nums.slice(0, maxIdx)
        const right = nums.slice(maxIdx + 1)
        return new TreeNode(max, constructMaximumBinaryTree(left), constructMaximumBinaryTree(right))
    }
    return null
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글