洛谷鏈接:https://www.luogu.com.cn/problem/P1827
題目囉裏囉嗦,其實就是已知樹的先序和中序遍歷,求後序遍歷
import java.util.Scanner;
public class Main {
static String a,b;
public static void end(int x,int y,int p,int q) { //x~y爲前序遍歷 p~q爲中序遍歷
if(x>y || p>q) {
return;
} else {
int i=b.indexOf(a.charAt(x)); //在中序隊列中查找根節點的位置上
end(x+1,x+i-p,p,i-1); //遞歸左子樹
end(x+i-p+1,y,i+1,q); //遞歸右子樹
System.out.print(a.charAt(x));
}
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
b=in.next(); //中序遍歷
a=in.next(); //先序遍歷
int L=a.length()-1; //下標從0開始;
end(0,L,0,L);
}
}