题解 | #重建二叉树#

重建二叉树

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

前序的一个元素一定是二叉树的根节点。利用这一点,不断将中序数组分成两个数组,分别为左子树和右子树。

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function reConstructBinaryTree(pre, vin)
{
    // write code here
    if(!pre.length || !vin.length){
        return null
    }
    let root = pre[0]
    let tnode = new TreeNode(root)
    let index = vin.indexOf(root)
    tnode.left = reConstructBinaryTree(pre.slice(1,index+1),vin.slice(0,index))
    tnode.right = reConstructBinaryTree(pre.slice(index+1),vin.slice(index+1))
    return tnode




}
module.exports = {
    reConstructBinaryTree : reConstructBinaryTree
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-08 13:15
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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