二叉搜索树
Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 32768/32768 K (Java/Others)
Problem Description
判断两序列是否为同一二叉搜索树序列
Input
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
Output
如果序列相同则输出YES,否则输出NO
Sample Input
2
567432
543267
576342
0
Sample Output
YES
NO
思路:
题意:给出一个序列,建立二叉排序树;再给出n个序列,分别建立二叉排序树,判断这n棵树是否和第一棵树是同一棵树。
方法:建树、判断序列长度和先序遍历是否相同。
AC代码:
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <queue>
using namespace std;
struct node
{
int data;
node *lc;
node *rc;
};
int p,q;
int pre[11],pre2[11];
//建二叉排序树
void create(node *&root,int t)
{
if(root==NULL)
{
root=new node;
root->data=t;
root->lc=NULL;
root->rc=NULL;
}
else if(t< root->data) create(root->lc,t);
else create(root->rc,t);
}
void preorder(node *root)
{
if(root)
{
//if(flag!=0) cout<<" ";
pre[p++]=root->data;
//flag=1;
preorder(root->lc);
preorder(root->rc);
}
}
void preorder2(node * root)
{
if(root)
{
//if(flag!=0) cout<<" ";
pre2[q++]=root->data;
//flag=1;
preorder2(root->lc);
preorder2(root->rc);
}
}
int main()
{
int n;
char a[11],b[11];//第一个序列和与它比较的序列
while(cin>>n&&n!=0)//要比较n个序列
{
//第一个序列建树并得到先序遍历结果
node *root=NULL;
cin>>a;
for(int i=0;i<strlen(a);i++)
{
create(root,a[i]-'0');
}
p=0;
preorder(root);
//与第一个序列比较的n个序列
for(int i=0;i<n;i++)
{
//根据序列建树
node *root2=NULL;
cin>>b;//输入序列
for(int j=0;j<strlen(b);j++)
{
create(root2,b[j]-'0');
}
//若与第一个序列长度不同则不可能是一棵树
if(strlen(b)!=strlen(a))
{
cout<<"NO"<<endl;
continue;
}
q=0;
int flag=0;//标志序列是否相等
preorder2(root2);
for(int j=0;j<q;j++)
{
if(pre[j]!=pre2[j])
{
flag=1;
cout<<"NO"<<endl;//不相等
break;
}
}
if(!flag) cout<<"YES"<<endl;//相等
}
}
return 0;
}