面试题七:重建二叉树

输入某二叉树的前序遍历和中序遍历结果,请重建二叉树,假设不含重复数字
分析:前序遍历中的根节点在序列的第一个,根节点在中序遍历结果序列中可以将左右子树分开

 BinaryTreeNode Construct( int A[ ] , int B[ ]){
        if( A ==null || B=null ||A.length<=0)
            return null;
         int Aend=A.length-1;
         int Bend=B.length-1;
        return ConstructCore( A , 0,Aend,B,0,Bend) 

    }
    BinaryTreeNode ConstructCore( int A[ ] ,int Abe., int Aend, 
                                  int B[ ],int Bbe, int Bend){
            //前序的第一个数字为根节点
            int rootvalue= A [Abe];//当前树的根
            BinaryTreeNode root=new BinaryTreeNode();
            root.value=rootvalue;
            root.L=null;
            root.R=null;
            //叶子节点,直接返回
            if( A[Abe] ==A[ Aend]) 
            {   if(B[Bbe]==B[ Bend]&&A[Abe]==B[Bbe])
                        return root;
                else System.out.print( "输入参数错误");
            }
            //在中序中寻找根节点的位置
            int rootB= Bbe;   
            while( Bend>=rootB && B[rootB] !=root.value)
                    rootB++;

            if( B[rootB] !=rootvalue &&  Bend==rootB))
                    System.out.print( "输入参数错误");

            //确定前序数组左右子树区间
             int Llength=rootB-Bbe;
             int ALend=Abe+Llength; 

           //构建左右子树
           if( Llength>0 )
                    root.L=ConstructCore( A,Abe+1,ALend,B,Bbe,rootB-1) ;
           if( Llength <Aend- Abe)
                    root.R=ConstructCore( A,ALend+1,Aend,B,rootB+1,Bend) ;
            return root;
    }

 

posted @ 2020-03-29 14:20  浪波激泥  阅读(195)  评论(0编辑  收藏  举报