sdut原题链接
二叉排序树
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
二叉排序树的定义是:或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。 今天我们要判断两序列是否为同一二叉排序树
Input
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉排序树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉排序树。(数据保证不会有空树)
Output
Example Input
2
123456789
987654321
432156789
0
Example Output
NO
NO
Hint
Author
以下为accepted代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct node
{
char date;
struct node *left;
struct node *right;
}BinTree;
int flag;
BinTree * Insert(BinTree *rt, char x)//二叉搜索树的插入算法
{
if(!rt)//若原树为空,生成并返回一个结点的二叉搜索树
{
rt = (BinTree *)malloc(sizeof(BinTree));
rt->date = x;
rt->left = rt->right = NULL;
}
else//开始找要插入元素的位置
{
if(x < rt->date)
rt->left = Insert(rt->left, x);
else if(x > rt->date)
rt->right = Insert(rt->right, x);
}
return rt;
}
void judge(BinTree *rt1, BinTree *rt2)//判断两个二叉搜索树是否相同
{
if(rt1 == NULL || rt2 == NULL)///判断两个二叉搜索树是否为空
return;
if(rt1 && rt2)
{
if(rt1->date != rt2->date)
return;
else
{
flag++;
judge(rt1->left, rt2->left);
judge(rt1->right, rt2->right);
}
}
}
int main()
{
int n, i, len;
char st1[24], st2[24];
while(scanf("%d", &n) != EOF && n)
{
BinTree *root = NULL;
scanf("%s", st1);
len = strlen(st1);
for(i = 0; i < len; i++)
{
root = Insert(root, st1[i]);//调用二叉搜索树的插入函数
}
for(i = 0; i < n; i++)
{
scanf("%s", st2);
BinTree *root1 = NULL;
flag = 0;
for(int j = 0; j < len; j++)
{
root1 = Insert(root1, st2[j]);//调用二叉搜索树的插入函数
}
judge(root, root1);//调用判断两个二叉搜索树是否相同的函数
if(flag == len)
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}
/***************************************************
User name: jk160630
Result: Accepted
Take time: 0ms
Take Memory: 112KB
Submit time: 2017-02-08 16:41:37
****************************************************/