04-树4 是否同一棵二叉搜索树(25 分)
给定一个插入序列就可以唯一确定一棵二叉搜索树。然而,一棵给定的二叉搜索树却可以由多种不同的插入序列得到。例如分别按照序列{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
大意:先给出一棵二叉树搜索树作为初始树,再给出其他的二叉搜索树,判断新的二叉树与初始二叉树是否相同
附上AC代码:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <list>
#include <map>
#include <stack>
#include <queue>
using namespace std;
#define ll long long
typedef struct Tree{
int data;
Tree *l,*r;
}*BiTree;
bool check[20];
void build(BiTree &T,int e)
{
if(!T)
{
T = new Tree;
T->data = e;
T->l = T->r = NULL;
return;
}
if(!T->l && e < T->data)
{
/*BiTree temp = new Tree;
temp->l = temp->r = NULL;
T->l = temp;
temp->data = e;*/
T->l = new Tree;
T->l->l = T->l->r = NULL;
T->l->data = e;
return;
}
if(!T->r && e > T->data)
{
/*BiTree temp = new Tree;
temp->l = temp->r = NULL;
T->r = temp;
temp->data = e;*/
T->r = new Tree;
T->r->l = T->r->r = NULL;
T->r->data = e;
return;
}
if(e > T->data)
build(T->r,e);
else
build(T->l,e);
return;
}
bool juge(BiTree T,int e)
{
if(!check[T->data] && e != T->data)
return false;
check[T->data] = 1;
if(e == T->data)
return true;
if(e < T->data)
return juge(T->l,e);
else
return juge(T->r,e);
}
int main()
{
int n,l;
while(cin >> n&&n)
{
cin >> l;
BiTree T ;
T = NULL;
for(int i = 0;i < n;i++)
{
int x;
cin >> x;
build(T,x);
}
while(l--)
{
int f = 0;
memset(check,0,sizeof(check));
for(int i = 0;i < n;i++)
{
int x;
cin >> x;
if(!juge(T,x))
f = 1;
}
if(f)
cout << "No" <<endl;
else
cout << "Yes" <<endl;
}
}
//cout << "AC" <<endl;
return 0;
}