题解 | #重建二叉树#

重建二叉树

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

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

function reConstructBinaryTree(pre, vin) {
    if (!pre.length || !vin.length) {
        return null;
    }

    // shift用于把数组中第一个元素删除,并返回其元素值
    const root = new TreeNode(pre.shift());
    const index = vin.indexOf(root.val);
    //方法可提取字符串或数组的某个部分,并以新的字符串或数组返回被提取的部分。
    //slice(start,end) 包含start,不包含end,提取了左子树
    root.left = reConstructBinaryTree(pre, vin.slice(0, index));
    //slice(start) 从start开始到数组结尾,提取到右子树
    root.right = reConstructBinaryTree(pre, vin.slice(index + 1));
    return root;
}
module.exports = {
    reConstructBinaryTree: reConstructBinaryTree,
};

全部评论

相关推荐

03-27 11:55
上海大学 运营
1900+能进面吗?
offer快到怀里来叭:全a都进不了
投递携程等公司10个岗位 > 携程求职进展汇总
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务