1. 程式人生 > >重建二叉樹(根據前序和中序遍歷結果)

重建二叉樹(根據前序和中序遍歷結果)

public TreeNode reConstructBinaryTree(int [] pre,int [] in) {         return build(pre,0,pre.length-1,in,0,in.length-1);     }     public TreeNode build(int[]preorder,int start1,int end1,int[]inorder,int start2,int end2){ if(start1>end1||start2>end2) return null; int rootval=preorder[start1]; //前序第一個結點為根 System.out.print(rootval+" "); TreeNode root=new TreeNode(rootval);int index=indexfindinorder(inorder,start2,end2,rootval);//在中序找到該根節點下標 root.left=build(preorder,start1+1,index+start1,inorder,start2,start2+index-1);//左子樹 root.right=build(preorder,index+start1+1,end1,inorder,start2+index+1,end2);//右子樹 return root; } private int indexfindinorder(int[] inorder, int start, int end,int rootval) {//