zoukankan      html  css  js  c++  java
  • 树---重建二叉树

    重建二叉树

    题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

    分析:

    前序遍历:先访问根à前序遍历左子树à前序遍历右子树

    中序遍历:先中序遍历左子树à访问根à中序遍历右子树

    后序遍历:先后序遍历左子树à后序遍历右子树à访问根

    此题有前序和中序:

    前:pre:{1,2,4,7,3,5,6,8}

    中:vin:{4,7,2,1,5,3,8,6}

    根:pre[0]à1,index为3

    左子树:vin_left{4,7,2}    pre_left:{2,4,7}

    右子树:vin_right{5,3,8,6} pre_right{3,5,6,8}

    然后递归找出左子树和右子树

    /* function TreeNode(x) {
    
        this.val = x;
    
        this.left = null;
    
        this.right = null;
    
    } */
    
    function reConstructBinaryTree(pre, vin)
    
    {
    
        // write code here
    
        if(pre.length==0||vin.length==0){
    
            return null
    
        }
    
        const index=vin.indexOf(pre[0])
    
        const left=vin.slice(0,index)
    
        const right=vin.slice(index+1)
    
        return {
    
            val:pre[0],
    
            left:reConstructBinaryTree(pre.slice(1,index+1),left),
    
            right:reConstructBinaryTree(pre.slice(index+1),right)
    } }
  • 相关阅读:
    redis内存模型、内存使用的优化
    【转】[Andriod]Xposed和VirtualXposed
    https详解
    http详解
    补码
    浮点数的二进制表示
    Go随机数
    ECDSA--圆锥曲线数字签名算法原理(摘wikepedia)
    Linux命令备忘
    【Windows】系统命令
  • 原文地址:https://www.cnblogs.com/mlebk/p/12599682.html
Copyright © 2011-2022 走看看