# 剑指offer之编程（四）

`import java.util.*;public class Main10 {public static void main(String[] args) {int[] pre = {1,2,4,7,3,5,6,8};        int[] in = {4,7,2,1,5,3,8,6};        solve(pre, in);}public static void solve(int []pre,int []in)  //pre为前序遍历，in为中序遍历{if(pre.length<1)  //没有元素就返回{return;}else if(pre.length==1)  //只有一个元素{System.out.println(pre[0]);  //输出这个元素}else{//在中序中找到当前根节点位置int index = 0;for(int i=0;i<in.length;i++){if(pre[0]==in[i]){index = i;}}//左半部分的前序int [] leftPre = new int[index];System.arraycopy(pre, 1, leftPre, 0, index);//右半部分的前序int len = pre.length-index-1;int [] rightPre = new int[len];System.arraycopy(pre, index+1, rightPre, 0, len);//左边部分的中序int [] leftIn = new int[index];System.arraycopy(in, 0, leftIn, 0, index);//左半部分的中序int rlen = in.length-index-1;int [] rightIn = new int[rlen];System.arraycopy(in, index+1, rightIn, 0, rlen);//递归地求解左右子树solve(leftPre, leftIn);solve(rightPre, rightIn);System.out.println(pre[0]);  //输出根}}}class TreeNode  //树节点的类{int data;TreeNode leftNode;TreeNode rightNode;public TreeNode(int data){this.data = data;}}`

0 0