package JianZhioffer; // 输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。 //递归,进入helperZ之前用整体进入后分左右 public class test07 { public static void main(String[] args) { int []preorder={3,9,20,15,7}; int []inorder={9,3,15,20,7}; TreeNode tr=buildTree(preorder, inorder); int x=0; } public static TreeNode buildTree(int[] preorder, int[] inorder) { if(preorder.length==0||inorder.length==0){ return null; } TreeNode result=helper(0, preorder.length-1, 0,inorder.length-1,preorder, inorder); return result; } public static TreeNode helper(int prestart,int preend,int instart,int inend,int []preorder,int []inorder){ if( prestart>preend){ return null; } TreeNode tr=new TreeNode(preorder[prestart]); if(prestart==preend){ return tr; } int r=preorder[prestart]; int k=0; for(int i=instart;i<=inend;i++){ if(inorder[i]==r){ k=i; break; } } int x=k-instart; int y=inend-k; tr.left=helper(prestart+1, prestart+x,instart,k-1, preorder, inorder); tr.right=helper(preend-y+1, preend,k+1,inend, preorder, inorder); return tr; } }