二叉搜索树
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2679 Accepted Submission(s): 1170
Problem Description
判断两序列是否为同一二叉搜索树序列
Input
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
Output
如果序列相同则输出YES,否则输出NO
Sample Input
2 567432 543267 576342 0
Sample Output
YES NO
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<algorithm>
using namespace std;
int n, up;
char pret[11], pres[11];
typedef struct NODE
{
char c;
struct NODE *lc, *rc;
} Node;
void finds(Node *&t, Node *&s)
{
if( t->c<s->c )
{
if( t->rc==NULL )
{
t->rc=s;
return;
}
else finds(t->rc, s);
}
else
{
if( t->lc==NULL )
{
t->lc=s;
return;
}
else finds(t->lc, s);
}
}
void CreateTree(Node *&t)
{
char ch;
ch=getchar();
if( ch=='\n' ) return;
Node *s;
s=(Node *)malloc(sizeof(Node));
s->c=ch;
s->lc=s->rc=NULL;
finds(t, s);
CreateTree(t);
}
void pretorder(Node *&t)
{
if( t )
{
pret[up]=t->c; up++;
pretorder(t->lc);
pretorder(t->rc);
}
}
void presorder(Node *&t)
{
if( t )
{
pres[up]=t->c; up++;
presorder(t->lc);
presorder(t->rc);
}
}
void inorder(Node *&t)
{
if( t )
{
inorder(t->lc);
cout<<t->c<<" ";
inorder(t->rc);
}
}
void postorder(Node *&t)
{
if( t )
{
postorder(t->lc);
postorder(t->rc);
cout<<t->c<<" ";
}
}
bool judge()
{
if( strcmp(pres, pret)==0 ) return true;
return false;
}
void destroy(Node *&t)
{
// if( t->lc==NULL && t->rc==NULL ) free(t);
if( t )
{
destroy(t->lc);
destroy(t->rc);
free(t);
}
}
int main()
{
Node *t, *s;
while( cin>>n && n )
{
getchar();
t=(Node *)malloc(sizeof(Node));
//t=s;
cin>>t->c;
t->lc=t->rc=NULL;
CreateTree(t);
up=0;
pretorder(t);
pret[up]=0;
// inorder(t); cout<<endl;
// postorder(t); cout<<endl;
for(int i=0; i<n; i++)
{
up=0;
s=(Node *)malloc(sizeof(Node));
cin>>s->c;
s->lc=s->rc=NULL;
CreateTree(s);
presorder(s);
// inorder(s);
pres[up]=0;
// cout<<pret<<endl;
// cout<<pres<<endl;
if( judge() ) cout<<"YES\n";
else cout<<"NO\n";
destroy(s);
}
}
return 0;
}