Check if two binary search trees are the same

input

Integer n, indicating that there are several binary trees to be compared with this binary tree
Integer sequence, used to determine a binary search tree
Next is n sequence, indicating n binary search trees

2
567432
543267
576342
0 (end of table)

output

YES/NO

YES
NO

ideas

First restore the sequence to a binary search tree, and then use the char[] array to record its preorder and inorder traversal [^foot], the same record of the preorder and inorder traversal of n binary trees to be tested, if two The preorder traversal and inorder traversal of the tree are the same, so they are the same tree.

Function name Function incoming outgoing
build() restore binary search tree Integer, binary search tree pointer
aft() post-order traversal tree pointer
pre() preorder traversal tree pointer
mid() Inorder traversal tree pointer
#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;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325676742&siteId=291194637