后面补充
import java.util.*;
public class Test16 {
private static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; left=null;right=null;}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
int count = scanner.nextInt();
int[] preArr = new int[count];
int[] inArr = new int[count];
for (int i = 0; i < count; i++) {
preArr[i] = scanner.nextInt();
}
for (int i = 0; i < count; i++) {
inArr[i] = scanner.nextInt();
}
TreeNode node = name(preArr, inArr, 0, preArr.length-1, 0, inArr.length-1);
ArrayList<Integer> list = new ArrayList<>();
print(node,list);
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i));
if (list.size()-1!=i) {
System.out.print(" ");
}
}
}
}
public static TreeNode name(int[] preArr,int[] inArr,int startPre,int endPre,int startIn,int endIn) {
if ( startIn > endIn) {
return null;
}
TreeNode tree = new TreeNode(preArr[startPre]);
for ( int i = startIn ; i <= endIn ; i++ ) {
if ( preArr[startPre] == inArr[i]) {
tree.left = name(preArr, inArr, startPre+1, i-startIn+startPre, startIn, i-1);
tree.right = name(preArr, inArr, i-startIn+startPre+1, endPre, i+1, endIn);
break;
}
}
return tree;
}
private static void print(TreeNode node,ArrayList<Integer> list) {
if (node == null)
return;
print(node.left,list);
print(node.right,list);
// System.out.print(node.val + " ");
list.add(node.val);
}
}