Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
使用遞歸,每次都取中點,作為當前部分的根節(jié)點隐轩,然后左邊的部分作為其左子樹识啦,右邊的部分作為其右子樹
下面的兩個方法一樣的克伊,一個使用了幫助函數(shù)一個沒有钙蒙。
var sortedArrayToBST = function(nums) {
var help = function(left,right){
if (left>right)
return null;
var mid = left+parseInt((right-left)/2);
var node = new TreeNode(nums[mid]);
var leftn = help(left,mid-1);
var rightn = help(mid+1,right);
if (leftn)
node.left = leftn;
if (rightn)
node.right = rightn;
return node;
};
return help(0,nums.length-1);
};
var sortedArrayToBST = function(nums) {
var len = nums.length;
if (len!==0) {
var mid = parseInt(len/2);
var node = new TreeNode(nums[mid]);
var left = sortedArrayToBST(nums.slice(0,mid));
var right = sortedArrayToBST(nums.slice(mid+1,len));
if (left)
node.left = left;
if (right)
node.right = right;
return node;
}
return null;