public TreeNode reConstructBinaryTree(int [] pre,int [] in) { if (pre==null || in==null) return null; return dfs(pre,0,pre.length-1,in,0,in.length-1); } private TreeNode dfs(int[] pre, int ps, int pe, int[] in, int ins, int ine) { //一般发生在pre下标ps或者pe的值处于in在区间ins和ine的两端处 if (ps>pe || ins>ine) return null; if (ps==pe) { TreeNode tn=new TreeNode(pre[ps]); return tn; } int temp = pre[ps]; int index = getIndex(temp,in,ins,ine); //ins index-1 左子树 index+1 ine 右子树 //ps+1 ps+1+index-1-ins=index+ps-ins 左子树 index+ps-ins+1 pe右子树 TreeNode left = dfs(pre,ps+1,index+ps-ins,in,ins,index-1); TreeNode right = dfs(pre,index+ps-ins+1,pe,in,index+1,ine); TreeNode root = new TreeNode(temp); root.left=left; root.right=right; return root; } private int getIndex(int temp,int[] in, int ins, int ine) { for (int i=ins;i<=ine;i++){ if(in[i]==temp){ return i; } } return 0; }