二叉排序树
Time Limit: 1000MS Memory limit: 65536K
题目描述
二叉排序树的定义是:或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。 今天我们要判断两序列是否为同一二叉排序树
输入
开始一个数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>
typedef struct node
{
char data;
struct node *lchild,*rchild;
}tree;
int f;
void creat(tree *&root,char key) //注意这个地方root的传递
{
if(root == NULL)
{
root = (tree *)malloc(sizeof(tree));
root->data = key;
root->lchild = root->rchild = NULL;
}
else
{
if(root->data > key)
creat(root->lchild,key);
else
creat(root->rchild,key);
}
}
void judge(tree *root1,tree *root2)
{
if(!root1&& !root2)
{
return ;
}
else if((root1 && !root2) || (!root1 && root2))
{
f = 1;
return ;
}
else if(root1->data == root2->data)
{
judge(root1->lchild,root2->lchild);
judge(root1->rchild,root2->rchild);
}
else
{
f = 1;
return ;
}
}
void dlr(tree *root)
{
if(root == NULL)
return ;
else
{
printf("%c",root->data);
dlr(root->lchild);
dlr(root->rchild);
}
}
int main()
{
int n;
char str1[1000],str2[1000];
while(~scanf("%d",&n))
{
int len;
tree *root1,*root2;
if(n == 0)
break;
else
{
root1 = NULL;
scanf("%s",str1);
len = strlen(str1);
for(int i = 0;i < len;i++)
{
creat(root1,str1[i]);
}
while(n--)
{
f = 0;
root2 = NULL;
scanf("%s",str2);
len = strlen(str2);
for(int i = 0;i < len;i++)
{
creat(root2,str2[i]);
}
judge(root1,root2);
if(f)
printf("NO\n");
else
printf("YES\n");
}
}
}
return 0;
}