题解 | #重建二叉树#

重建二叉树

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

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function reConstructBinaryTree(pre, vin)
{
  	//若先序数组为空 则为null(递归中止)
    if(pre[0]==undefined){
        return null
    }
  
  	//将先序的第一个元素作为root
    const node = new TreeNode(pre[0])
    let vi =vin.indexOf(pre[0])
    
    //以该元素为定位 切分中序数组为左右中序数组
    const vleft = vin.slice(0,vi)
    const vright = vin.slice(vi+1,vin.length)
    
    //同理将先序数组切分
    const pleft = pre.slice(1,vleft.length+1)
    const pright = pre.slice(vleft.length+1)
    
    //递归构建树
    node.left = reConstructBinaryTree(pleft,vleft)
    node.right = reConstructBinaryTree(pright,vright)
    return node
     
}
module.exports = {
    reConstructBinaryTree : reConstructBinaryTree
};
全部评论

相关推荐

12-24 14:26
东北大学 Java
一只乌鸦:重邮+东北,好经典的学校
最后再改一次简历
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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