Description
对应给定的一个序列可以唯一确定一棵二叉排序树。然而,一棵给定的二叉排序树却可以由多种不同的序列得到。例如分别按照序列{3,1,4}和{3,4,1}插入初始为空的二叉排序树,都得到一样的结果。你的任务书对于输入的各种序列,判断它们是否能生成一样的二叉排序树。
Input
输入包含若干组测试数据。每组数据的第1行给出两个正整数N (n < = 10)和L,分别是输入序列的元素个数和需要比较的序列个数。第2行给出N个以空格分隔的正整数,作为初始插入序列生成一颗二叉排序树。随后L行,每行给出N个元素,属于L个需要检查的序列。
简单起见,我们保证每个插入序列都是1到N的一个排列。当读到N为0时,标志输入结束,这组数据不要处理。
Output
对每一组需要检查的序列,如果其生成的二叉排序树跟初始序列生成的二叉排序树一样,则输出"Yes",否则输出"No"。
Sample
Input
4 2
3 1 4 2
3 4 1 2
3 2 4 1
2 1
2 1
1 2
0
Output
Yes
No
No
#include <stdio.h>
#include <stdlib.h>
typedef struct BiTree {
int data;
struct BiTree *l, *r;
} Tree;
//Binary Sort Tree二叉排序树
//利用插入法构建二叉排序树
Tree *CreatBST(Tree *root, int key) {
if(!root) {//当前节点为空(叶子节点)
//相当于遍历二叉树,当找到叶子节点时证明找到了当前key应该插入的位置
root = (Tree*)malloc(sizeof(Tree));
root->data = key;
root->r = NULL;
root->l = NULL;
} else {//当前节点不为空则继续遍历(没找到叶子节点)
if(key > root->data) {
root->r = CreatBST(root->r, key);
} else {
root->l = CreatBST(root->l, key);
}
}
return root;
}
int flag;
void judge(Tree *root1, Tree *root2) {
//如果有一个是空,一个不是空,则直接判断为构成的二叉排序树不一样
if((!root1 && root2) || (root1 && !root2)) {
flag = 0;
return ;
}
//若两个都不为空
if(root1 && root2) {
//顶点不相等则判断为不一样,直接结束
if(root1->data != root2->data) {
flag = 0;
return;
}
//左右子树继续比较
judge(root1->l, root2->l);
judge(root2->r, root2->r);
}
}
int main() {
int n;//序列元素个数
int l;//需要比较的序列个数
Tree *root1;//初始序列
Tree *root2;//待比较序列
int key;
while(scanf("%d", &n) && n != 0) {
root1 = NULL;
root2 = NULL;
flag = 1;
scanf("%d", &l);
for(int i = 0; i < n; i++) {
scanf("%d", &key);
root1 = CreatBST(root1, key);
}
while(l--) {
for(int i = 0; i < n; i++) {
scanf("%d", &key);
root2 = CreatBST(root2, key);
}
judge(root1, root2);
if(flag == 0) {
printf("No\n");
} else {
printf("Yes\n");
}
}
}
return 0;
}