上面是將有序數組轉為二叉樹的代碼~ 二分查找的速度為O(log n), 遍歷二叉樹的速度為O(n) ...
/**
* 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)