[LeetCode] Convert Sorted Array to Binary Search Tree (JS)

nRecode·2020년 9월 8일
0

Algorithm

목록 보기
6/48

문제

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

입출력 예

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

접근

정렬된 배열이 입력으로 들어오고 이진탐색트리를 만들어야 한다.
정렬된 배열의 가운데 인덱스 값이 root.val가 될테고, 그 0번째 인덱스 부터 가운데 인덱스 전까지의 배열을 left 가운데 인덱스부터 마지막 인덱스까지 right 값으로 재귀를 돌리는 방법을 사용한다.

풀이

var sortedArrayToBST = function(nums) {
    if(!nums.length){
        return null;
    }
    // 정렬된 배열의 가운데 값
    let mid = Math.floor(nums.length / 2);
    let root = new TreeNode(nums[mid]); 
     
    // left와 right모두 진행한다.
    root.left = sortedArrayToBST(nums.slice(0,mid));
    root.right = sortedArrayToBST(nums.slice(mid + 1));
    
    return root;
};

😀

profile
안정성, 확장성 있는 서버를 구축하고 가꾸는 개발자를 목표로 공부하고 있습니다. 🤔🤔🤔🤔 부족하기에 맞지 않는 내용이 있을 수 있습니다. 가감없이 피드백 해주시면 정말 감사하겠습니다..🙏

0개의 댓글