7-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
鸣谢青岛大学周强老师补充测试数据!
其他求解的方法参考
https://blog.csdn.net/lafengxiaoyu/article/details/53351486
AC代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
using namespace std;
typedef struct BSTNode
{
int value;
//int flag;
BSTNode *left;
BSTNode *right;
}BS_Tree, *BSTree;
BSTree InsertBSTree(BSTree bsTree, int x)
{
if (bsTree == NULL)
{
bsTree = (BSTree)malloc(sizeof(BS_Tree));
bsTree->value = x;
bsTree->left = NULL;
bsTree->right = NULL;
//bsTree->flag = 0;
}
else
{
if (bsTree->value > x)
{
bsTree->left = InsertBSTree(bsTree->left, x);
}
else
{
bsTree->right = InsertBSTree(bsTree->right, x);
}
}
return bsTree;
}
bool CompareBST(BSTree t1, BSTree t2)
{
if (t1 == NULL && t2 == NULL)
return true;
else if ((t1 == NULL && t2 != NULL) || (t1 != NULL && t2 == NULL))
return false;
else if ((t1 != NULL && t2 != NULL) && (t1->value != t2->value))
return false;
else
{
if (CompareBST(t1->left, t2->left) == true && CompareBST(t1->right, t1->right)== true);
return true;
return false;
}
}
//bool check (BSTree T,int data)
//{
// if(T->flag) {
// if(data < T->value)
// return check(T->left,data);
// else if(data > T->value)
// return check(T->right,data);
// else
// return false;
// }else {
// if(data == T->value) { //是要找的结点
// T->flag = 1;
// return true;
// }
// else return false; //不是 不一致
// }
//}
//
//int judge(BSTree t, int n)
//{
// int i, v;
// int flag = 0;
// cin >> v;
// if (t->value != v)
// flag = 1;
// else
// t->flag = 1;
// for (i = 1; i < n; i++)
// {
// cin >> v;
// if ((!flag) && !check(t, v))
// flag = 1;
// }
// if (flag)
// return 0;
// else
// return 1;
//}
//void reset(BSTree t)
//{
// if (t->left) reset(t->left);
// if (t->right) reset(t->right);
// t->flag = 0;
//}
int main()
{
int n, l, data;
while (cin >> n)
{
if (n == 0)
break;
cin >> l;
BSTree tree = NULL;
BSTree temp = NULL;
for (int i = 0; i < n; i++)
{
cin >> data;
tree = InsertBSTree(tree, data);
}
for (int j = 0; j < l; j++)
{
temp = NULL;
for (int i = 0; i < n; i++)
{
cin >> data;
temp = InsertBSTree(temp, data);
}
if (CompareBST(tree, temp))
cout << "Yes" << endl;
else
cout << "No" << endl;
}
}
return 0;
}