判断两棵二叉搜索树是否相同

input

整数n,表示有几个二叉树要与本二叉树比较
整数序列,用来确定一棵二叉搜索树
接下来是n个序列,表示n棵二叉搜索树

2
567432
543267
576342
0(表结束)

output

YES/NO

YES
NO

思路

先将序列还原成二叉搜索树,再用char[]数组记录他的前序和中序遍历[^foot],同样的记录需测试的n个二叉树的前序和中序遍历,若两个树的前序遍历和中序遍历都相同,则他们是同一棵树。

函数名 功能 传入 传出
build() 还原二叉搜索树 整数、二叉搜索树指针
aft() 后序遍历 树指针
pre() 前序遍历 树指针
mid() 中序遍历 树指针
#include<stdio.h>
#include<iostream>
#include<cstring>
using namespace std;
struct Node{
Node *ltre;
Node *rtre;
int w;
}buf[50];
int a[30];
int loc,n,ind;
char p[25],m[25],pp[25],mm[25],str[25],st[25];

Node *create(){
buf[loc].ltre=buf[loc].rtre=NULL;
return &buf[loc++];
}

void pre(Node *t,char *p){
p[ind++]=t->w+'0';
if(t->ltre!=NULL){
    pre(t->ltre,p);
}
if(t->rtre!=NULL){
    pre(t->rtre,p);
}
}

void mid(Node *t,char *p){
if(t->ltre!=NULL){
    mid(t->ltre,p);
}
p[ind++]=t->w+'0';
if(t->rtre!=NULL){
    mid(t->rtre,p);
}
}



void build(int x,Node *t){

if(x>t->w){

    if(t->rtre==NULL){

        t->rtre=create();
        t->rtre->w=x;

        return;

    }
    build(x,t->rtre);

}
if(x<t->w){

    if(t->ltre==NULL){
        t->ltre=create();
        t->ltre->w=x;

        return;

    }
    build(x,t->ltre);
}

}




int main(){

while(scanf("%d",&n)!=EOF&&n!=0){
    loc=0;
    scanf("%s",&str);
    getchar();
    Node *T=create();

    for(int i=0;i<str[i]!=0;i++){//还原本二叉树
        build(str[i]-'0',T);
    }
    strcpy(p,"");
    strcpy(m,"");

    ind=0;
    pre(T,p);//得到前序遍历
    mid(T,m);//得到中序遍历
    strcat(p,m);
//    cout<<"p="<<p<<endl;
    while(n--){
        Node *t=create();
        strcpy(st,"");
        scanf("%s",&st);
        getchar();
        for(int i=0;i<st[i]!=0;i++){
            build(st[i]-'0',t);//还原测试二叉树
        }
        strcpy(pp,"");

        strcpy(mm,"");
        ind=0;
        pre(t,pp);
        mid(t,mm);
        strcat(pp,mm);
//        cout<<"pp="<<pp<<endl;
        puts(strcmp(p,pp)==0?"YES":"NO");
    }


}
return 0;
}

猜你喜欢

转载自blog.csdn.net/chunjiekid/article/details/79620864