/**
* 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) return null;
const result = new TreeNode(nums)
return result
};
function TreeNode(nums) {
if(nums.length){
const middleIndex = Math.floor(nums.length/2)
this.val = nums[middleIndex];
if(middleIndex>0){
this.left = new TreeNode(nums.slice(0, middleIndex));
} else {
this.left = null
}
if(middleIndex<nums.length-1){
this.right = new TreeNode(nums.slice(middleIndex+1));
} else {
this.right = null
}
} else { return null }
}
上面是将有序数组转为二叉树的代码~
二分查找的速度为O(log n), 遍历二叉树的速度为O(n)