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

代码实现:

public class BinaryTreeNode{
     int value;
     BinaryTreeNode left;
     BinaryTreeNode right;
}

 

public class Solution{
     public static BinaryTreeNode construct(int[] preorder,int[] inorder) throws Exception{
         if(preorder==null||inorder==null||preorder.length==0||inorder.length==0||preorder.length!=inorder.length){
                return null;
          }
          return constructCore(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
     }

     public static BinaryTreeNode constructCore(int[] preorder,int preStart,int preEnd,int[] inorder,int inStart,int inEnd) throws Exception{
          int rootValue=preorder[preStart];
          //创建一个树结点
          BinaryTreeNode root=new BinaryTreeNode();
          root.value=rootValue;
          root.left=null;
          root.right=null;
          //判断最后一个元素是否相等
          if(preStart==preEnd){
               if(inStart==inEnd&&preorder[preStart]==inorder[inStart]){
                      return root;
                }else{
                      throw new Exception("Invalid input");
                }
          }
          //查找当前树结点的值,对应中序遍历中的位置。找到该位置,确定该位置之前的为该结点的左子树序列,而之后的为该结点的右子树序列
          int rootInorder=inStart;
          while(rootInorder<=inEnd&&inorder[rootInorder]!=rootValue){
                 rootInorder++;
          }
          //计算该结点左子树的长度
          int leftLength=rootInorder-inStart;
          int leftPreEnd=preStart+leftLength;
          //左子树的长度大于0表示结点有左子树,而等于0,左子树为null
          if(leftLength>0){
                 root.left=constructCore(preorder,preStart+1,leftPreEnd,inorder,inStart,rootInorder-1);
          }
          //左子树的长度小于当前的序列的长度表示结点含有右子树,而相等表示,右子树为null。
           if(leftLength<preEnd-preStart){
                 root.right=constructCore(preorder,leftPreEnd+1,preEnd,inorder,rootInorder+1,inEnd);
           }
           return root;
     }

     public static void main(String[] args){
           int[] preorder={1,2,4,7,3,5,6,8};
           int[] inorder={4,7,2,1,5,3,8,6};
           try{
               BinaryTreeNode node=construct(preorder,inorder);
               preorder(node);
               System.out.println();
               inorder(node);   
           }catch(Exception e){
               e.printStackTrace();
           }           
     }

     //前序遍历
     public static void preorder(BinaryTreeNode node){
           if(node!=null){
               System.out.print(node.value+" ");
               preorder(node.left);
               preorder(node.right);
           }
     }

     //中序遍历
     public static void inorder(BinaryTreeNode node){
           if(node!=null){
               inorder(node.left);
               System.out.print(node.value+" ");
               inorder(node.right);
           }
      }
}

 

 posted on 2018-12-18 22:10  会飞的金鱼  阅读(116)  评论(0)    收藏  举报