hdu 3791 二叉搜索树(数据结构)

时间:2023-03-09 06:23:53
hdu 3791 二叉搜索树(数据结构)

二叉搜索树

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3420    Accepted Submission(s): 1496

Problem Description
判断两序列是否为同一二叉搜索树序列
Input
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
Output
如果序列相同则输出YES,否则输出NO
Sample Input
2
567432
543267
576342
Sample Output
YES
NO
Source

搜索二叉数的定义:

二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树

不算什么难题,纯粹的数据结构,二叉树的建立与遍历,就是注意下应该按照搜索二叉树的定义进行建树,然后将建立出来的树比较一下对应位置的数值是否相等即可。

 #include<iostream>
#include<vector>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include<algorithm> using namespace std;
struct nodes
{
int date;
struct nodes *left,*right;
}*tree,*cur;
struct nodes *Creat(int x)
{
cur = (struct nodes *)malloc(sizeof(struct nodes));
cur->left = NULL;
cur->right = NULL;
cur->date = x;
return cur;
};
struct nodes *build(int x,struct nodes *root)
{
if(root == NULL)
{
root = Creat(x);
}
else
{
if(x <= root->date)
root->left = build(x,root->left);
else
root->right = build(x,root->right);
}
return root;
}
int cnt;
void lookthrough(struct nodes *root,int digit[])
{
if(root != NULL)
{
digit[cnt++] = root->date;
lookthrough(root->left,digit);
lookthrough(root->right,digit);
}
}
int main(void)
{
int n,i,j,a[],b[],l;
char str[];
while(scanf("%d",&n),n)
{
scanf("%s",str);
tree = Creat(str[]-'');
l = strlen(str);
for(i = ; i < l; i++)
{
tree = build(str[i]-'',tree);
}
cnt = ;
lookthrough(tree,a); for(i = ; i < n; i++)
{
tree = NULL;
scanf("%s",str);
tree = Creat(str[] - '');
for(j = ; j < l; j++)
{
tree = build(str[j]-'',tree);
}
cnt = ;
lookthrough(tree,b);
int ans = ;
for(j = ; j < l; j++)
if(a[j] != b[j])
{
ans = ;
break;
} if(ans == )
printf("NO\n");
else
printf("YES\n");
}
}
return ;
}