LeetCode题库解答与分析——#108. 将有序数组转换为二叉搜索树ConvertSortedArrayToSearchBinaryTree

给定有序数组: [-10,-3,0,5,9],

0
/ \
-3   9
/   /
-10  5

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

/**
* Definition for a binary tree node.
* function TreeNode(val) {
*     this.val = val;
*     this.left = this.right = null;
* }
*/
/**
* @param {number[]} nums
* @return {TreeNode}
*/
var sortedArrayToBST = function(nums) {
if(nums.length==0){
return null;
}
var l=nums.length;
var half=parseInt(l/2);
var root=new TreeNode(nums[half]);
if(half==0){
return root;
}
var left=new Array(half);
var right=new Array(l-half-1);
for(var i=0;i<left.length;i++){
left[i]=nums[i];
}
root.left=arguments.callee(left);
for(var i=0;i<right.length;i++){
right[i]=nums[i+half+1];
}
root.right=arguments.callee(right);
return root;
};

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120