判断两序列是否为同一二叉搜索树序列
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
算法思想:
1、建树(建树的过程就是二叉搜索树插入元素的过程)。
2、通过判断前序遍历是否相同来判断是否为同一棵(当然也可以通过中序和后序)。
建树代码:
void create(BiNode *&root,char ch)///&引用的意思,这里需要修改root,所以需引用
{
if(root==NULL)//为空直接插入
{
root=(BiNode*)malloc(sizeof(BiNode));
root->data=ch;
root->lchild=NULL;
root->rchild=NULL;
}
else
{
if(ch < root->data)
create(root->lchild,ch);
else
create(root->rchild,ch);
}
}
完整代码:
#include<bits/stdc++.h>
using namespace std;
struct BiNode
{
char data;
BiNode *lchild;
BiNode *rchild;
};
char a[20];
int num;
void create(BiNode *&root,char ch)///&y引用的意思,这里需要修改root,所以需引用
{
if(root==NULL)//为空直接插入
{
root=(BiNode*)malloc(sizeof(BiNode));
root->data=ch;
root->lchild=NULL;
root->rchild=NULL;
}
else
{
if(ch < root->data)
create(root->lchild,ch);
else
create(root->rchild,ch);
}
}
void pre(BiNode *root)///前序遍历
{
if(root!=NULL)
{
a[num++]=root->data;
pre(root->lchild);
pre(root->rchild);
}
}
int main()
{
char str1[20],str2[20];
int n;
while(~scanf("%d",&n))
{
num=0;
char b[20],c[20];
BiNode *root;
root=NULL;
scanf("%s",str1);
for(int i=0; str1[i]; i++)
create(root,str1[i]);
pre(root);
strcpy(b,a);///将第一棵树前序遍历序列保存在b中
for(int i=0; i<n; i++)
{
num=0;
int flag=0;
BiNode *bt;
bt=NULL;
scanf("%s",str2);
for(int i=0; str2[i]; i++)
create(bt,str2[i]);
pre(bt);
strcpy(c,a);///将第二棵树前序遍历序列保存在c中
if(strcmp(b,c)!=0)
printf("NO\n");
else
printf("YES\n");
}
}
return 0;
}