题解 | #将升序数组转化为平衡二叉搜索树#

将升序数组转化为平衡二叉搜索树

https://www.nowcoder.com/practice/7e5b00f94b254da599a9472fe5ab283d

/*
 * function TreeNode(x) {
 *   this.val = x;
 *   this.left = null;
 *   this.right = null;
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param nums int整型一维数组 
 * @return TreeNode类
 */
function sortedArrayToBST( nums ) {
    // write code here
    if(nums.length == 0) {
        return null
    }
    if(nums.length == 1) {
        return treeNode(nums[0])
    }
    nums = nums.sort((a, b)=> a - b);
    let center = Math.floor(nums.length / 2);
    let leftNodes = nums.splice(0, center);
    let leftNodesSum = 0;
    for(let i = 0;i<leftNodes;i++){
        leftNodesSum = leftNodesSum + parseInt(leftNodes[i]);
    }
    console.log('leftNodes', leftNodes, leftNodesSum, nums)
    let max = leftNodesSum;
    let maxIndex = 0;
    for(let j =0;j<nums.length;j++) {
        if(nums[j] >= max) {
            max = nums[j];
            maxIndex = j;
            break;
        }
    }
    nums.splice(maxIndex, 1);
    return {
        val: max,
        left: sortedArrayToBST(leftNodes),
        right: sortedArrayToBST(nums)
    } 
}
function treeNode(val) {
    return {
        val,
        left: null,
        right: null
    }
}
module.exports = {
    sortedArrayToBST : sortedArrayToBST
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务