1. 程式人生 > >js將數組轉化為平衡二叉樹

js將數組轉化為平衡二叉樹

new oot int var console his log ray ===

function TreeNode(val) {
this.value = val;
}

var sortedArrayToBST = function (nums) {
if (nums.length === 0) {
return null;
}
if (nums.length === 1) {
return new TreeNode(nums[0]);
}
var mid = parseInt(nums.length / 2);
var root = new TreeNode(nums[mid]);
root.left = sortedArrayToBST(nums.slice(0, mid));
root.right = sortedArrayToBST(nums.slice(mid + 1));
return root;
}

var ss = sortedArrayToBST([-10, -3, 0, 5, 9]);
console.log(ss);

js將數組轉化為平衡二叉樹