题解 | #重建二叉树#

重建二叉树

https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6

function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
}

/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param preOrder int整型一维数组
 * @param vinOrder int整型一维数组
 * @return TreeNode类
 */
function reConstructBinaryTree(preOrder, vinOrder) {
    // write code here
    if (preOrder.length == 0) return null;
    let root = new TreeNode(preOrder[0]);
    console.log(root);
    let temp = vinOrder.indexOf(root.val);
    //   console.log('temp:',temp);
    root.left = reConstructBinaryTree(
        preOrder.slice(1, temp + 1),
        vinOrder.slice(0, temp)
    );
    root.right = reConstructBinaryTree(
        preOrder.slice(temp + 1),
        vinOrder.slice(temp + 1)
    );
    return root;
}
let root = reConstructBinaryTree([2], [2]);
console.log(root);


module.exports = {
    reConstructBinaryTree: reConstructBinaryTree,
};

全部评论

相关推荐

求个付费实习岗位:这种就是吃满时代红利又没啥技术水平,只能靠压力学生彰显优越感的老登,别太在意了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务