B - 二叉排序树
Description
二叉排序树的定义是:或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。 今天我们要判断两序列是否为同一二叉排序树
Input
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉排序树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉排序树。(数据保证不会有空树)
Output
Sample
Input
2
123456789
987654321
432156789
0
Output
NO
NO
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct tree
{
char data;
struct tree *l,*r;
}*root,*root1;
struct tree *create(char q,struct tree *root);
char a[11],b[11];
int k=1; //主函数外定义
void judge (struct tree *root,struct tree *root1);
int main()
{
int i;
int n;
while( ~scanf("%d",&n))
{
if(n== 0)break;
scanf("%s",a);
int len=strlen(a);
root=NULL;
for(i=0; i<len; i++)
{
root=create(a[i],root);
}
while(n–)
{
root1=NULL;
scanf("%s",b);
for(i=0; i<len; i++)
{
root1=create(b[i],root1);
}
k=1; //每次归1
judge(root,root1);
if(k==0)printf(“NO\n”);
else printf(“YES\n”);
}
}
return 0;
}
struct tree *create(char q,struct tree *root) //建立两种二叉树
{
if(!root)
{
root=(struct tree *)malloc(sizeof(struct tree));
root->data=q;
root->l=NULL;
root->r=NULL;
return root;
}
else
{
if(q>=root->data) //比根大的放右边
{
root->r=create(q,root->r);
}
else //否则放左边
{
root->l=create(q,root->l);
}
}
return root;
};
void judge (struct tree *root,struct tree *root1) //进行判断是否相等
{
if(root&&root1)
{
if(root->data!=root1->data)
{
k=0;
return ;
}
judge(root->l,root1->l);
judge(root->r,root1->r);
}
else if(root1||root) //题目已给没有重复字母,所以这个写不写都行
{
k=0;
return ;
}
}
来源:CSDN
作者:Are_you_ready
链接:https://blog.csdn.net/Are_you_ready/article/details/104175628