给定一个插入序列就可以唯一确定一棵二叉搜索树。然而,一棵给定的二叉搜索树却可以由多种不同的插入序列得到。例如分别按照序列{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 st[1000],no[1000];
int k = 1,x = 1,n,m,t = 0;
typedef int Key;
typedef struct Node{
Key key;
struct Node *left;
struct Node *right;
struct Node *fa;
}Node,*PNode;
void inserts(PNode *root,Key key){ //插入值到二叉搜索树立
PNode p = (PNode)malloc(sizeof(Node));
p->key = key;
p->left = p->right = p->fa = NULL;
if((*root) == NULL){
*root = p;
return;
}
if((*root)->left == NULL && (*root)->key >= key){
p->fa = (*root);
(*root)->left = p;
return;
}
if((*root)->right == NULL && (*root)->key <= key){
p->fa = (*root);
(*root)->right = p;
return;
}
if((*root)->key >= key)
inserts(&(*root)->left,key);
else if((*root)->key <= key)
inserts(&(*root)->right,key);
else return;
}
void Out(PNode *root){
if((*root) == NULL)return;
if(k)
st[t++] = (*root)->key;
else{
no[t++] = (*root)->key;
if(no[t-1] != st[t-1]) //比较两个数组各个值是否相等
x = 0;
}
Out(&(*root)->left);
Out(&(*root)->right);
}
void create(PNode *root,Key *keyArray){
for(int i = 0; i < m; i++)
inserts(root,keyArray[i]);
}
int main(){
while(scanf("%d",&m) && m){
cin >> n;
k = 1;
t = 0;
memset(st,0,sizeof(st));
Key nodeArray[m];
PNode root = NULL;
for(int i = 0; i < m; i++)
cin >> nodeArray[i];
create(&root,nodeArray);
Out(&root); //存主二叉搜索树到数组st里
//cout << root->key << endl;
k = 0;
while(n--){
PNode root = NULL;
x = 1;
t = 0;
memset(no,0,sizeof(no));
for(int i = 0; i < m; i++)
cin >> nodeArray[i];
create(&root,nodeArray);
Out(&root); //存子二叉搜索树到数组no里
if(x)cout << "Yes" << endl;
else cout << "No" << endl;
}
}
return 0;
}
二叉搜索树基本操作参见:https://blog.csdn.net/Touch_2011/article/details/6831924