题意:判断两序列是否为同一二叉搜索树序列
思路:创建了二叉搜索树之后,随便用一个遍历方法来判断两棵二叉树的每个结点的值是不是相等的就可以了。
代码:
#include <iostream>
using namespace std;
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
typedef struct node //二叉树结点
{
struct node *lchild;
struct node *rchild;
char key;
}Node, *BinNode;
int flag;
void Insert(BinNode &root, char value) //插入结点
{
BinNode temp = (BinNode)malloc(sizeof(Node));
temp->lchild = NULL;
temp->rchild = NULL;
temp->key = value;
if(root == NULL)
{
root = temp;
}
if(root->key == value)
{
return ;
}
else if(root->key > value)
{
Insert(root->lchild, value);
}
else
{
Insert(root->rchild, value);
}
}
void GetAns(BinNode root1, BinNode root2) //用先序遍历来判断两棵树的结构是不是一样的
{
if(root1 != NULL && root2 != NULL)
{
if(root1->key == root2->key) //如果先序遍历的时候两棵树的值都一样,那flag加一,最后再判断flag的长度是不是等于主树的结点个数
{
flag ++;
}
if(root1->lchild != NULL && root2->lchild != NULL)
GetAns(root1->lchild, root2->lchild);
if(root1->rchild != NULL && root2->rchild != NULL)
GetAns(root1->rchild, root2->rchild);
}
}
int main()
{
int n;
char k[11];
while(scanf("%d", &n)!=EOF)
{
if(n == 0)
break;
memset(k, 0, sizeof(k));
cin>>k;
BinNode root = NULL;
int len = strlen(k);
for(int i = 0; i < len; i++)
{
Insert(root, k[i]);
}
while(n--)
{
flag = 0;
BinNode p = NULL;
memset(k, 0, sizeof(k));
cin>>k;
len = strlen(k);
for(int i = 0; i < len; i++)
Insert(p, k[i]);
GetAns(root, p);
if(flag == len) //比较主树的节点个数和主树与要比较的树的结构相同的节点的个数
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
}
return 0;
}