两个字符串,其长度n均小于等于26。 第一行为前序遍历,第二行为中序遍历。 二叉树中的结点名称以大写字母表示:A,B,C....最多26个结点。
输入样例可能有多组,对于每组测试样例, 输出一行,为后序遍历的字符串。
ABC BAC FDXEAG XDEFAG
BCA XEDGAF
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
judge(sc.nextLine(), sc.nextLine());
}
}
public static void judge(String str1,String str2){
if (str1.length() == 0) return;
int num = str2.indexOf(str1.charAt(0));
judge(str1.substring(1, num + 1), str2.substring(0, num));
judge(str1.substring(num + 1), str2.substring(num + 1));
System.out.print(str1.charAt(0));
}
} import java.util.Scanner;
public class Main{
/*
思路:递归
一颗树的左子树的后序遍历+右子树的后序遍历+该树根节点的值为该树的后序遍历序列
*/
private static int count = 0;//记录当前选择的是前序遍历序列中的第几个节点
public static void main(String[] args){
try(Scanner in = new Scanner(System.in)){
String s1 = in.nextLine(),s2 = in.nextLine();
char[] a = s1.toCharArray(),b = s2.toCharArray();
System.out.println(helper(a,b,0,a.length));
}
}
//以a[count]将位于[s,e)的b分成两半,即找到以a[count]为根节点的左右子树,再对其进行递归
public static String helper(char[] a,char[] b,int s,int e){
if(s >= e) return "";
char c = a[count++];
int i = s;
while(i < e){
if(b[i] == c) break;
i++;
}
String l = helper(a,b,s,i),r = helper(a,b,i + 1,e),res = l + r + c;
return res;
}
}