给定一个插入序列就可以唯一确定一棵二叉搜索树。然而,一棵给定的二叉搜索树却可以由多种不同的插入序列得到。例如分别按照序列{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>
#include <queue>
using namespace std;
struct Tree
{
int Ele;
struct Tree *Left;
struct Tree *Right;
};
typedef struct Tree* T;
T Insert(T root,int key);
bool judge(T a,T b);
void Get(T a,int *aa,int *na);
bool Equal(int *a,int nn,int *b);
void Print(int *a,int n);
int n,L;
int main()
{
T Sam,Test;
int x;
while (1)
{
cin>>n;
if (n==0)
{
break;
}
cin>>L;
Sam=NULL;
for (int i=0;i<n;i++)
{
cin>>x;
Sam=Insert(Sam,x);
}
for (int i=0;i<L;i++)
{
Test=NULL;
for (int j=0;j<n;j++)
{
cin>>x;
Test=Insert(Test,x);
}
if (judge(Sam,Test))
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
}
return 0;
}
T Insert(T root,int key)
{
if (root==NULL)
{
root=(T)malloc(sizeof(struct Tree));
root->Ele=key;
root->Left=root->Right=NULL;
return root;
}
T now;
if (key>root->Ele)
{
now=Insert(root->Left,key);
root->Left=now;
}
else if (key<root->Ele)
{
now=Insert(root->Right,key);
root->Right=now;
}
return root;
}
bool judge(T a,T b)
{
int aa[15],bb[15],nn;
memset(aa,0,sizeof(aa));
memset(bb,0,sizeof(bb));
Get(a,aa,&nn);
Get(b,bb,&nn);
// Print(aa,nn);
// Print(bb,nn);
if (Equal(aa,nn,bb))
{
return true;
}
return false;
}
void Get (T a,int *aa,int *na)
{
queue<T>q;
T t=NULL;
*na=0;
if (a==NULL)
{
*na=-1;
return;
}
q.push(a);
while (!q.empty())
{
t=q.front();
q.pop();
aa[(*na)++]=t->Ele;
if (t->Left)
{
q.push(t->Left);
}
if (t->Right)
{
q.push(t->Right);
}
}
return;
}
bool Equal(int *a,int nn,int *b)
{
for (int i=0;i<nn;i++)
{
if (a[i]!=b[i])
{
return false;
}
}
return true;
}
void Print(int *a,int n)
{
printf("\n");
for (int i=0;i<n;i++)
{
printf("%d ",a[i]);
}
printf("\n");
}