import java.util.Scanner;
public class Main {
static String a[];//前
static String b[];//中
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
sc.nextLine();
while(n-->0){
a=sc.nextLine().split(" ");
b=sc.nextLine().split(" ");
Node root= f(0,a.length-1,0,b.length-1);
g(root);
System.out.println();
}
}
private static void g(Node root) {//后序
if(root.left!=null)
g(root.left);
if(root.right!=null)
g(root.right);
System.out.print(root.num+" ");
}
private static Node f(int i, int j,int q,int w) {
if(i==j) return new Node(a[i]);
if(i>j) return null;
Node temp = new Node(a[i]);
int k=q;
for (; k <w; k++) {
if(a[i].equals(b[k]))
break;
}
temp.left=f(i+1,k+i-q,q,k-1);
temp.right=f(j+k-w+1,j,k+1,w);
return temp;
}
}
class Node{
Node left;
Node right;
String num;
public Node(String num) {
super();
this.num = num;
}
}
测试二叉树:
前 9 10 12
中 10 12 9
后 12 10 9
前 3 6 7 11
中 6 3 11 7
后 6 11 7 3
前 4 8 9 10 12
中 8 4 10 12 9
后 8 12 10 9 4
前 2 4 8 9 10 12 5
中 8 4 10 12 9 2 5
后 8 12 10 9 4 5 2
前 1 2 4 8 9 10 12 5 3
中 8 4 10 12 9 2 5 1 3
后 8 12 10 9 4 5 2 3 1
前 1 2 4 8 9 10 12 5 3 6 7 11
中 8 4 10 12 9 2 5 1 3 6 7 11
后 8 12 10 9 4 5 2 11 7 6 3 1