您的位置:首页 > 其它

hdu 3791 二叉搜索树

2014-02-28 16:55 369 查看

二叉搜索树

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2549 Accepted Submission(s):
1109


[align=left]Problem Description[/align]
判断两序列是否为同一二叉搜索树序列

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

[align=left]Output[/align]
如果序列相同则输出YES,否则输出NO

[align=left]Sample Input[/align]

2

567432

543267

576342

0

[align=left]Sample Output[/align]

YES

NO

[align=left]Source[/align]
浙大计算机研究生复试上机考试-2010年

[align=left]Recommend[/align]
notonlysuccess

/**
2
567432
543267
576342

**/

#include<iostream>
#include<stdio.h>
#include<cstring>
#include<cstdlib>
using namespace std;

struct node
{
int rp;
struct node *lchild;
struct node *rchild;
};
struct node *root;
int len=0;

void mem(struct node *p)
{
p->rp=0;
p->lchild=NULL;
p->rchild=NULL;
}
void insert_ecs(struct node **p,int x)
{
if( (*p) == NULL)
{
(*p)=(struct node*)malloc(sizeof(struct node));
mem(*p);
(*p)->rp=x;
return;
}
if( (*p)->rp>x)
insert_ecs(&(*p)->lchild,x);
else
insert_ecs(&(*p)->rchild,x);
}

void serch1(struct node *p,int *a)
{
a[++len]=p->rp;
if(p->lchild!=NULL)
serch1(p->lchild,a);
if(p->rchild!=NULL)
serch1(p->rchild,a);
}
void serch2(struct node *p,int *a)
{
if(p->lchild!=NULL)
serch1(p->lchild,a);
a[++len]=p->rp;
if(p->rchild!=NULL)
serch1(p->rchild,a);
}
void delete_ecs(struct node *p)
{
if(p->lchild!=NULL)
delete_ecs(p->lchild);
if(p->rchild!=NULL)
delete_ecs(p->rchild);
free(p);
}
void cs(int *a,int *b,int n)
{
int i;
for(i=1;i<=n;i++)
printf("%d ",a[i]);
printf("\n");
for(i=1;i<=n;i++)
printf("%d ",b[i]);
printf("\n");
}
int  main()
{
int n,i,j,k1,k2;
char c[20];
int s1[20],s2[20],s3[20];
while(scanf("%d",&n)>0)
{
if(n==0)break;
scanf("%s",c);
k1=strlen(c);
root=NULL;
for(i=0;i<k1;i++)
{
insert_ecs(&root,c[i]-'0');
}
len=0;
serch1(root,s1);
len=0;
serch2(root,s2);
while(n--)
{
scanf("%s",c);
k2=strlen(c);
if(k2!=k1){ printf("NO\n"); continue;}

struct node *head=NULL;
for(j=0;j<k2;j++)
insert_ecs(&head,c[j]-'0');
len=0;
serch1(head,s3);
for(j=1;j<=k1;j++)
if(s1[j]!=s3[j])break;
if(j<=k1)
{
printf("NO\n");
delete_ecs(head);
continue;
}
len=0;
serch2(head,s3);

for(j=1;j<=k2;j++)
if(s2[ j ] !=s3[ j ])break;
if(j<=k2)
{
delete_ecs(head);
printf("NO\n");
continue;
}
printf("YES\n");
}
delete_ecs(root);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: