第一次写二叉搜索树 这题很基础 比较适合我这种新手 只需要建好树后 前序或后序遍历即可
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
typedef int keytype;
int as[30],ss[30],n=0,leap;
typedef struct node
{
keytype key;
struct node *lchild;
struct node *rchild;
struct node *parent;
}Node ,*Pnode;
void insert(Pnode *root,keytype key)//插入结点
{
Pnode p=(Pnode)malloc(sizeof(Node));
p->key=key;
p->lchild=p->rchild=p->parent=NULL;
if(*(root)==NULL){
*root=p;
return;
}
if((*root)->lchild==NULL&&key<(*root)->key){
p->parent=*root;
(*root)->lchild=p;
return;
}
if((*root)->rchild==NULL&&key>(*root)->key){
p->parent=*root;
(*root)->rchild=p;
}
if((*root)->key>key){
insert(&(*root)->lchild,key);
}
else if((*root)->key<key){
insert(&(*root)->rchild,key);
}
else
return;
}
void Creat(Pnode *root,int lenth,keytype arry[])
{
for(int i=0;i<lenth;i++)
insert(root,arry[i]);
}
void frontorder(Pnode root)
{
if(root){
ss[n++]=root->key;
frontorder(root->lchild);
frontorder(root->rchild);
}
}
void frontorder1(Pnode ex)
{
if(ex){
as[n++]=ex->key;
frontorder1(ex->lchild);
frontorder1(ex->rchild);
}
}
int main(void)
{
int m;
while(scanf("%d",&m)!=EOF&&m)
{
Pnode root=NULL;
int lenth,ex1[30];
char ex[30];
memset(as,0,sizeof(as));
scanf("%s",ex);
n=0;
lenth=strlen(ex);
for(int i=0;i<lenth;i++)
ex1[i]=ex[i]-'0';
Creat(&root,lenth,ex1);
frontorder1(root);
while(m--)
{
Pnode tmp=NULL;
int da1[30];
char da[30];
leap=0;
scanf("%s",da);
for(int i=0;i<lenth;i++)
da1[i]=da[i]-'0';
Creat(&tmp,lenth,da1);
n=0;
frontorder(tmp);
for(int i=0;i<lenth;i++)
if(as[i]!=ss[i]) {
leap=1;
break;
}
if(leap==0) printf("YES\n");
else printf("NO\n");
}
}
}