题解 | #重建二叉树#

重建二叉树

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,
};

全部评论

相关推荐

苍蓝星上艾露:这简历。。。可以试试我写的开源简历优化工具https://github.com/weicanie/prisma-ai
点赞 评论 收藏
分享
tttk_:就是人多。 有的是条件和你差不多然后没在od待过的人。 所以就拿这个筛你了。 就和卡学历一样,人太多了。 从公司角度,这样做节省精力,更方便。 没办法谁叫现在人多呢
第一份工作能做外包吗?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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