题目描述
Time Limit: 1000 ms
Memory Limit: 256 mb
判断两序列是否为同一二叉搜索树序列
输入输出格式
输入描述:
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
输出描述:
如果序列相同则输出YES,否则输出NO
输入输出样例
输入样例#:
复制
2
567432
543267
576342
0
输出样例#:
复制
YES
NO
题目来源
浙江大学机试题
#include<iostream>
#include<cstring>
using namespace std;
char a[15],b[15];
int o = 0,m = 0;
struct tree{
char num;
struct tree *lchild,*rchild;
};
struct tree *create(struct tree *&p,char x){
if(p == NULL){
p = (tree*)malloc(sizeof(tree));
p ->num = x;
p ->lchild = NULL;
p ->rchild = NULL;
}
else if(x < p ->num){
create(p ->lchild,x);
}
else if(x > p->num){
create(p ->rchild,x);
}
return p;
}
void inorder1(struct tree *p,int i){
if(p != NULL){
inorder1(p ->lchild,i);
a[o++] = p ->num;
inorder1(p ->rchild,i);
}
}
void inorder2(struct tree *p,int i){
if(p != NULL){
inorder2(p ->lchild,i);
b[m++] = p ->num;
inorder2(p ->rchild,i);
}
}
int main(){
struct tree *p = NULL;
int n;
cin>>n;
while(n--){
o = 0; //数组下标归零
m = 0;
for(int i = 0;i < 15;i++){ //数组清空
a[i] = '\0';
b[i] = '\0';
}
struct tree *p = NULL; //比较两个数,就要建两个根节点
struct tree *q = NULL;
cin>>a; //把序列输入数组
int len1 = strlen(a);
cin>>b;
int len2 = strlen(b);
if(len1 != len2) //长度不等直接NO
{
cout<<"NO"<<endl;
continue;
}
for(int i = 0;i < len1;i++){
p = create(p,a[i]); //用a得序列建树
}
for(int i = 0;i < len2;i++){//同理
q = create(q,b[i]);
}
inorder1(p,0); //如果排序树相同,中序遍历一定相同,并覆盖a,b得记录
inorder2(q,0);
int f = 0;
for(int l = 0,k = 0; l < len1,k < len2;l++,k++ ){
if(a[l] != b[k]){ //比较中序序列
f = 1;
break;
}
}
if(f == 0) cout<<"YES"<<endl;
else if(f == 1) cout<<"NO"<<endl;
}
return 0;
}