题目描述
判断两序列是否为同一二叉搜索树序列
输入
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
输出
如果序列相同则输出YES,否则输出NO
样例输入
2
567432
543267
576342
0
样例输出
YES
NO
来源
2010年浙江大学计算机及软件工程研究生机试真题
二叉排序树定义:
二叉排序树或者是一棵空树,或者是具有下列性质的二叉树:
- 若左子树不空,则左子树上所有结点的值均小于它的根结点的值;
- 若右子树不空,则右子树上所有结点的值均大于它的根结点的值;
- 左、右子树也分别为二叉排序树;
- 没有键值相等的节点。
纯模拟建二叉搜索数的过程,之后遍历一下看建的树是否相同就ok啦
#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
string s, t;
int a[2005], b[2005];
void createtree(string s, int c[2005]){
int len = s.length();
for(int i = 0; i < len; i++){
int t = s[i]-'0';
for(int j = 1; j <= 2000;){
if(c[j] == -1){
c[j] = t;
break;
}
else if(c[j] > t)
j = j*2;
else
j = j*2+1;
}
}
}
int main()
{
int n, i;
while(scanf("%d", &n)!=EOF){
cin >> s;
memset(a, -1, sizeof(a));
createtree(s, a);
while(n--){
memset(b, -1, sizeof(b));
cin >> t;
createtree(t, b);
for(i = 0; i <= 2000; i++){
if(a[i]!=b[i])
break;
}
if(i&2000)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
}
return 0;
}