题解 | #重建二叉树#

重建二叉树

http://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
    }
    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
};
全部评论

相关推荐

看到这个内容真是闹麻了。。。。。。现在有了AI以后很多人面试都会作弊吗? 那对老老实实面试的人岂不是不公平....
重生之我要干前端:放宽心,作弊很明显的,面试官也不是傻子,而且这世上更多的肯定是依靠自己的知识的人,所以放宽心提升自己最重要
点赞 评论 收藏
分享
07-01 13:37
门头沟学院 Java
steelhead:不是你的问题,这是社会的问题。
点赞 评论 收藏
分享
下北澤大天使:你是我见过最美的牛客女孩😍
点赞 评论 收藏
分享
评论
6
收藏
分享

创作者周榜

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