Problem Description
判断两序列是否为同一二叉搜索树序列
Input
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
Output
如果序列相同则输出YES,否则输出NO
Sample Input
2
567432
543267
576342
Sample Output
YES
NO
NO
Source
浙大计算机研究生复试上机考试-2010年
#include<cstdio>
#include<string.h>
#include<cmath>
using namespace std;
const int maxn=+;
char S[+],s[+],Tree[maxn],tree[maxn];
//建立原始二叉树
void BuildTree(char c,int i)
{
if(Tree[i]=='#')Tree[i]=c;
else
{
if(c<Tree[i])BuildTree(c,*i);
if(c>Tree[i])BuildTree(c,*i+);
}
}
//建立判断二叉树
void Buildtree(char c,int i)
{
if(tree[i]=='#')tree[i]=c;
else
{
if(c<tree[i])Buildtree(c,*i);
if(c>tree[i])Buildtree(c,*i+);
}
}
int main()
{
int n;
while(scanf("%d",&n)==&&n)
{
//输入原始数组
scanf("%s",&S);
int Len=strlen(S);
//建原始树
memset(Tree,'#',sizeof(Tree));
for(int i=;i<Len;i++)
{
BuildTree(S[i],);
}
while(n--)
{
//输入判断树组
scanf("%s",&s);
int len=strlen(s);
if(len!=Len)printf("NO\n");
else
{
//建判断树
memset(tree,'#',sizeof(tree));
for(int i=;i<len;i++)
{
Buildtree(s[i],);
}
int res=;
for(int i=;i<maxn;i++)
{
if(tree[i]!=Tree[i])
{
printf("NO\n");
res=;
break;
}
}
if(res==)printf("YES\n");
}
}
}
return ;
}