题目描述
二叉排序树的定义是:或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。 今天我们要判断两序列是否为同一二叉排序树
输入
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉排序树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉排序树。(数据保证不会有空树)
输出
示例输入
2 123456789 987654321 432156789 0
示例输出
NO NO
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char a[20],b[20],str1[20],str2[20];
int x,y;
struct node
{
char data;
struct node *l;
struct node *r;
};
struct node *create(struct node *p, char x)
{
if(p==NULL)
{
p=(struct node *)malloc(sizeof (struct node ));
p->data=x;
p->l=NULL;
p->r=NULL;
}
else
{
if(x<=p->data)
p->l=create(p->l,x);
else
p->r=create(p->r,x);
}
return p;
}
void pre1(struct node *p)
{
if(p!=NULL)
{
a[x++]=p->data;
pre1(p->l);
pre1(p->r);
}
}
void pre2(struct node *p)
{
if(p!=NULL)
{
b[y++]=p->data;
pre2(p->l);
pre2(p->r);
}
}
int main()
{
int n,i;
while(~scanf("%d",&n)&&n)
{
scanf("%s",str1);
struct node *root1=NULL;
for(i=0;str1[i]!='\0';i++)
{
root1=create(root1,str1[i]);
}
x=0;
pre1(root1);
a[x]='\0';
while(n--)
{
scanf("%s",str2);
struct node *root2=NULL;
for(i=0;str2[i]!='\0';i++)
{
root2=create(root2,str2[i]);
}
y=0;
pre2(root2);
b[y]='\0';
if(strcmp(a,b)==0)
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}
本文探讨了如何通过序列判断它们是否能够形成相同的二叉排序树,包括输入格式、实现步骤以及示例输出。
1521

被折叠的 条评论
为什么被折叠?



