-
题目描述:
-
判断两序列是否为同一二叉搜索树序列
-
输入:
-
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
-
输出:
-
如果序列相同则输出YES,否则输出NO
-
样例输入:
-
2 567432 543267 576342 0
-
样例输出:
-
YES NO
import java.util.Scanner;
public class Main {
static char[][]a=new char[11][3];
static char[][]b=new char[11][3];
static String c;
public static void hebinga(char x,char y){
if(x>y){
if(a[x-'0'][0]=='#') a[x-'0'][0]=y;
else hebinga(a[x-'0'][0],y);
}
else{
if(a[x-'0'][1]=='#') a[x-'0'][1]=y;
else hebinga(a[x-'0'][1],y);
}
}
public static void hebingb(char x,char y){
if(x>y){
if(b[x-'0'][0]=='#') b[x-'0'][0]=y;
else hebingb(b[x-'0'][0],y);
}
else {
if(b[x-'0'][1]=='#') b[x-'0'][1]=y;
else hebingb(b[x-'0'][1],y);
}
}
public static int pan(){
for(int i=0;i<11;i++)
for(int j=0;j<3;j++)
if(a[i][j]!=b[i][j])
return 0;
return 1;
}
public static void main(String[] args){
Scanner in=new Scanner(System.in);
while(true){
int n=in.nextInt();
if(n==0) break;
for(int i=0;i<11;i++)
a[i][0]=a[i][1]=a[i][2]='#';
c=in.next();
a[c.charAt(0)-'0'][2]='@';
for(int i=1;i<c.length();i++){
hebinga(c.charAt(0),c.charAt(i));
a[c.charAt(i)-'0'][2]='@';
}
for(int k=0;k<n;k++){
for(int i=0;i<11;i++)
b[i][0]=b[i][1]=b[i][2]='#';
c=in.next();
b[c.charAt(0)-'0'][2]='@';
for(int i=1;i<c.length();i++){
hebingb(c.charAt(0),c.charAt(i));
b[c.charAt(i)-'0'][2]='@';
}
int t=pan();
if(t==0) System.out.println("NO");
else System.out.println("YES");
}
}
in.close();
}
}