您的位置:首页 > 其它

HDU 3791 二叉搜索树

2015-09-12 18:14 246 查看


二叉搜索树

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 3584 Accepted Submission(s): 1575



Problem Description

判断两序列是否为同一二叉搜索树序列



Input

开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。

接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。

接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。



Output

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



Sample Input

2
567432
543267
576342
0




Sample Output

YES
NO




Source

浙大计算机研究生复试上机考试-2010年



Recommend

notonlysuccess | We have carefully selected several similar problems for you: 3787 3790 3789 3788 1710
ACcode
#include <map>
#include <queue>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#define maxn 10000+5
using namespace std;
struct Tree{
    int num;
    Tree *l,*r;
}*my;
int a[50],b[50],cnt;
Tree *creat(int x){
    Tree *t=(Tree *)malloc(sizeof(Tree));
    t->l=NULL;
    t->r=NULL;
    t->num=x;
    return t;
}
Tree *join(Tree *s,int x){
    Tree *t;
    if(s==NULL){
        t=creat(x);
        s=t;
    }
    else {
        if(x<=s->num)
            s->l=join(s->l,x);
        else
            s->r=join(s->r,x);
    }
    return s;
}
void fun(Tree *t){
    if(t!=NULL){
        a[cnt++]=t->num;
        fun(t->l);
        fun(t->r);
    }
}
int main(){
    int n;
    while(scanf("%d",&n)&&n){
        my=NULL;
        char ss[30];
        scanf("%s",ss);
        int l=strlen(ss);
        memset(a,0,sizeof(a));
        for(int i=0;i<l;++i)
            my=join(my,ss[i]-'0');
        cnt=0;
        fun(my);
        for(int i=0;i<l;++i)b[i]=a[i];
        while(n--){
            my=NULL;
            char ss[30];
            scanf("%s",ss);
            for(int i=0;i<l;++i)
                my=join(my,ss[i]-'0');
                cnt=0;
            fun(my);
            int i=0;
            /*for(i=0;i<l;i++)cout<<a[i]<<' ';
            cout<<'\12';
            for(i=0;i<l;i++)cout<<b[i]<<' ';
            cout<<'\12';*/
            for(i=0;i<l;i++)
                if(a[i]!=b[i]){
                    printf("NO\n");
                    break;
                }
            if(i>=l)
                printf("YES\n");
        }
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: