题目
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.
Example:
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
思路
- 将传入的数组,取中间的数作为当前节点的值,两侧的子数组构成子树
- 两侧的子数组按照步骤1进行,直到只剩下一个值,那么就结束递归
var sortedArrayToBST = function(nums) {
return run(nums);
};
var run = function(nums) {
if (nums.length === 0) return null;
const midIndex = Math.floor(nums.length / 2);
const nowNode = new TreeNode(nums[midIndex]);
const leftNums = nums.slice(0, midIndex);
const rightNums = nums.slice(midIndex + 1);
nowNode.left = run(leftNums);
nowNode.right = run(rightNums);
return nowNode;
}