1009.二叉搜索树

题目描述:
判断两序列是否为同一二叉搜索树序列
输入:
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
输出:

如果序列相同则输出YES,否则输出NO

样例输入:
2
567432
543267
576342
0
样例输出:
YES
NO
#include<stdio.h>
#include<string.h> 

struct Node{
    Node *lchild,*rchild;
    int c;
}tree[110];
int loc;
Node *creat(){
    tree[loc].lchild=tree[loc].rchild=NULL;
    return &tree[loc++];
}

char str1[25],str2[25];
int size1,size2;
char *str;
int *size;
void postorder(Node *t){
    if(t->lchild!=NULL){
        postorder(t->lchild);
    }
    if(t->rchild!=NULL){
        postorder(t->rchild);
    }
    str[(*size)++]=t->c+'0';
}

void inorder(Node *t){
    if(t->lchild!=NULL){
        inorder(t->lchild);
    }
    str[(*size)++]=t->c+'0';
    if(t->rchild!=NULL){
        inorder(t->rchild);
    }
}

Node *insert(Node *t,int x){
    if(t==NULL){
        t=creat();
        t->c=x;
        return t;
    }
    else if(x<t->c){
        t->lchild=insert(t->lchild,x);
    }
    else if(x>-t->c){
        t->rchild=insert(t->rchild,x);
    }
    return t;
}

int main(){
    int n;
    char temp[12];
    while(scanf("%d",&n)!=EOF && n!=0){
        loc=0;
        Node *t=NULL;
        scanf("%s",temp);
        for(int i=0;temp[i]!=0;i++){
            t=insert(t,temp[i]-'0');
        }
        size1=0;
        str=str1;
        size=&size1;
        postorder(t);
        inorder(t);
        str1[size1]=0;
        while(n--!=0){
            scanf("%s",temp);
            Node *t2=NULL;
            for(int i=0;temp[i]!=0;i++){
                t2=insert(t2,temp[i]-'0');
            }
            size2=0;
            str=str2;
            size=&size2;
            postorder(t2);
            inorder(t2);
            str2[size2]=0;
            puts(strcmp(str1,str2)==0 ? "YES" : "NO");
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/bernieloveslife/p/9736619.html