二叉排序树
Time Limit: 1000 ms Memory Limit: 65536 KiB
Submit Statistic Discuss
Problem Description
二叉排序树的定义是:或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。 今天我们要判断两序列是否为同一二叉排序树
Input
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉排序树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉排序树。(数据保证不会有空树)
Output
Sample Input
2
123456789
987654321
432156789
0
Sample Output
NO
NO
Hint
Source
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct tree
{
char data;
struct tree*left,*right;
};
int flag;
struct tree*insert(struct tree*root,char x)//插入函数
{
if(!root)
{
root=(struct tree*)malloc(sizeof(struct tree));
root->data=x;
root->left=NULL;
root->right=NULL;
}
else
{
if(x<root->data)
{
root->left=insert(root->left,x);
}
else if(x>root->data)
root->right=insert(root->right,x);
}
return root;//一直运行到最后,直到创建了一个新的root,在一层层的往回递归,赋值,到主函数里的时候直接拿出树根就可以
}
void judge(struct tree*root1,struct tree*root2)//判断两个树的二叉排序是不是一样的
{
if(root1==NULL&&root2==NULL)
return ;
else if(root1&&root2)
{
if(root1->data!=root2->data)
return ;
else
{
flag++;
judge(root1->left,root2->left);
judge(root1->right,root2->right);
}
}
}
int main()
{
int n,len,i;
char s1[54],s2[54];
while(~scanf("%d",&n)&&n)
{
scanf("%s",s1);
len=strlen(s1);
struct tree*root=NULL;
for(i=0;i<len;i++)
{
root=insert(root,s1[i]);
}
while(n--)
{
flag=0;
struct tree*root1=NULL;
scanf("%s",s2);
for(i=0;i<len;i++)
{
root1=insert(root1,s2[i]);//记住,要把root1写出来
}
judge(root,root1);
if(flag==len)
printf("YES\n");
else printf("NO\n");
}
}
return 0;
}