九度题目1009:二叉搜索树

来源:互联网 发布:程序员的思维方式 编辑:程序博客网 时间:2024/05/21 11:08

原题链接:http://ac.jobdu.com/problem.php?pid=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 <queue>#include <stdlib.h>#include <string.h>using namespace std; struct biTree{    struct biTree *lchild,*rchild;    int data;}; struct biTree *create(struct biTree *root,int val){    if(root==NULL){        root=(struct biTree*)malloc(sizeof(struct biTree));        root->data=val;        root->rchild=root->lchild=NULL;    }    else if(val<root->data)   root->lchild=create(root->lchild,val);    else root->rchild=create(root->rchild,val);    return root;} int compare(struct biTree *root1,struct biTree *root2){    queue<struct biTree*>q1,q2;    q1.push(root1);    q2.push(root2);    while (!q1.empty()&&!q2.empty()){        struct biTree *t1=q1.front();        struct biTree *t2=q2.front();        if(t1->lchild!=NULL) q1.push(t1->lchild);        if(t1->rchild!=NULL) q1.push(t1->rchild);        if(t2->lchild!=NULL) q2.push(t2->lchild);        if(t2->rchild!=NULL) q2.push(t2->rchild);        if(t1->data!=t2->data) return 0;        //printf("%d %d",t1->data,t2->data);        q1.pop();        q2.pop();    }    while(!q1.empty()||!q2.empty())  return 0;    return 1;} int main(){    int n,i,j;    char str[10];    while(scanf("%d",&n)!=EOF&&n){        struct biTree *root=NULL;        scanf("%s",str);        for(i=0;str[i];i++){            root=create(root,str[i]-'0');        }        for(i=0;i<n;i++){            scanf("%s",str);            struct biTree *t=NULL;            for(j=0;str[j];j++){                t=create(t,str[j]-'0');            }            int result=compare(root,t);            if(result){                printf("YES\n");            }            else{                printf("NO\n");            }        }    }    return 0;}


如果文章有什么错误或者有什么建议,欢迎提出,大家共同交流,一起进步

文章转载请注明出处,请尊重知识产权

0 0
原创粉丝点击