您的位置:首页 > 其它

二叉搜索树HDU - 3791

2020-05-11 04:10 113 查看

判断两序列是否为同一二叉搜索树序列
Input
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
Output
如果序列相同则输出YES,否则输出NO
Sample Input
2
567432
543267
576342
0
Sample Output
YES
NO

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N=1e5+10;
bool flag;
struct node
{
int val;
node *l,*r;
};
node *insert(node *p,int x)
{
if(p==NULL)
{
node *q=new node;
q->val=x;
q->l=q->r=NULL;
return q;
}
else
{
if(p->val>x)
p->l=insert(p->l,x);
else p->r=insert(p->r,x);
return p;
}
}
void check(node *root,node *room)
{
if(root!=NULL&&room!=NULL)
{
check(root->l,room->l);
if(root->val!=room->val)
flag=0;
check(root->r,room->r);
}
else if(root!=NULL||room!=NULL)
flag=0;
}
int main()
{
int n;
while(~scanf("%d",&n)&&n)
{
node *root=NULL;
char str[20];
scanf("%s",str);
for(int i=0; i<strlen(str); i++)
root=insert(root,str[i]-'0');///标准树
for(int i=0; i<n; i++)
{
flag=1;
node *room=NULL;///判断树
scanf("%s",str);
for(int j=0; j<strlen(str); j++)
room=insert(room,str[j]-'0');
check(root,room);
if(flag)printf("YES\n");
else printf("NO\n");
}
}
return 0;
}
Starry_Sky_Dream 原创文章 50获赞 4访问量 2323 关注 私信
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: