js将数组转化为平衡二叉树

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);
    原文作者:逸_风
    原文地址: https://www.cnblogs.com/zxk5625/p/9399324.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞