Problem Description
判断两序列是否为同一二叉搜索树序列
Input
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
Output
如果序列相同则输出YES,否则输出NO
Sample Input
2 567432 543267 576342 0
Sample Output
YES NO
思路:
判断两序列是否为同一二叉搜索树序列,只需按照所给序列构造相应的二叉排序树,然后问题只要转换成两颗树是否相同即可,即判断其前根序列和中根序列(或后根序列和中根序列)是否相同即可,但由于二叉排序树的特殊性,只需其前根序列相同,两棵树就相同。
按照这思路,代码如下;
#include<iostream>
#include<string>
using namespace std;
struct binarysearchnode {
int value;
binarysearchnode* lchild;
binarysearchnode* rchild;
};//定义二叉查找树
typedef binarysearchnode* binarysearchtree;
//插入
binarysearchtree insert(binarysearchtree tree, int value)
{
binarysearchnode *temp = tree;
binarysearchnode *parent = NULL;//插入位置父节点
while (temp != NULL)//寻找插入位置
{
parent = temp;
if (temp->value < value)
{
temp = temp->rchild;
}
else {
temp = temp->lchild;
}
}
temp = new binarysearchnode();
temp->value = value;
if (tree == NULL)
{
tree = temp;
}
else
{
if (parent->value > value)
parent->lchild = temp;
else
parent->rchild = temp;
}
return tree;
}
//前序
int flag = 0;
void pre(binarysearchtree tree, int *p)
{
if (tree != NULL)
{
p[flag++] = tree->value;
pre(tree->lchild,p);
pre(tree->rchild,p);
}
}
/*//中序
void in(binarysearchtree tree, int *p)
{
if (tree != NULL)
{
in(tree->lchild, p);
p[flag++] = tree->value;
in(tree->rchild, p);
}
}*/
int main()
{
int n,k;
string s;
binarysearchtree tree;
int min[10];//记录被比较二叉排序树前序
//int min1[10];//记录被比较二叉排序树中序
int cmp[10];//记录要比较二叉排序树前序
//int cmp1[10];//记录要比较二叉排序树中序
while (cin >> n)
{
if (n == 0) break;
tree = NULL;
cin >> s;
int l = s.size();
for (int j = 0; j < l; j++)
{
int va = s[j] - '0';
tree = insert(tree, va);
}
flag = 0;
pre(tree, min);
while (n--)
{
cin >> s;
tree = NULL;
for (int j = 0; j < l; j++)
{
int va = s[j] - '0';
tree = insert(tree, va);
}
flag = 0;
pre(tree, cmp);
for (k = 0; k < l; k++)
{
if (min[k] != cmp[k])
{
cout << "NO" << endl;
break;
}
}
if (k == l)
cout << "YES" << endl;
}
}
return 0;
}