给定一个插入序列就可以唯一确定一棵二叉搜索树。然而,一棵给定的二叉搜索树却可以由多种不同的插入序列得到。例如分别按照序列{2, 1, 3}和{2, 3, 1}插入初始为空的二叉搜索树,都得到一样的结果。于是对于输入的各种插入序列,你需要判断它们是否能生成一样的二叉搜索树。
输入格式:
输入包含若干组测试数据。每组数据的第1行给出两个正整数N (≤10)和L,分别是每个序列插入元素的个数和需要检查的序列个数。第2行给出N个以空格分隔的正整数,作为初始插入序列。随后L行,每行给出N个插入的元素,属于L个需要检查的序列。
简单起见,我们保证每个插入序列都是1到N的一个排列。当读到N为0时,标志输入结束,这组数据不要处理。
输出格式:
对每一组需要检查的序列,如果其生成的二叉搜索树跟对应的初始序列生成的一样,输出“Yes”,否则输出“No”。
输入样例:
4 2
3 1 4 2
3 4 1 2
3 2 4 1
2 1
2 1
1 2
0
输出样例:
Yes
No
No
采用数组存储搜索二叉树,每次判断两个数组是否相同
#include <bits/stdc++.h>
using namespace std;
int n,l;
int t[20][3],tt[20][3];
void it(int root,int a){
if(a == root)return;
if(a < root){
if(t[root][1]!=0){
root = t[root][1];
it(root,a);
}else{
t[root][1] = a;
}
}else if(a>root){
if(t[root][2]!=0){
root = t[root][2];
it(root,a);
}else{
t[root][2] = a;
}
}else return;
}
void itt(int roott,int a){
if(a == roott)return;
if(a < roott){
if(tt[roott][1]!=0){
roott = tt[roott][1];
itt(roott,a);
}else{
tt[roott][1] = a;
}
}else if(a>roott){
if(tt[roott][2]!=0){
roott = tt[roott][2];
itt(roott,a);
}else{
tt[roott][2] = a;
}
}else return;
}
int main()
{
cin>>n;
int fff = 0;
while(n != 0){
cin>>l;
memset(t,0,sizeof(t));
int root;
cin>>root;
for(int i = 2;i<=n;i++){
int a;
cin>>a;
it(root,a);
}
while(l--){
memset(tt,0,sizeof(tt));
int roott;
cin>>roott;
for(int i = 2;i<=n;i++){
int a;
cin>>a;
itt(roott,a);
}
int flag = 1;
if(root!=roott)flag = 0;
for(int i = 1;i<=n&&flag;i++){
if(t[i][1] == tt[i][1] && t[i][2] == tt[i][2]){
continue;
}else {
flag = 0;
break;
}
}
if(fff)cout<<endl;
else fff = 1;
if(flag)cout<<"Yes";
else cout<<"No";
}
cin>>n;
}
return 0;
}