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;
};
끝 😀