二叉搜索树 HDU

来源:互联网 发布:linux 挂载iso什么意思 编辑:程序博客网 时间:2024/06/08 17:54


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

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


代码一:

#include<stdio.h>#include<string.h>#include<vector>using namespace std;struct node{    char val;    node * left;    node * right;    node():left(NULL),right(NULL) {}};char res[12],a[12],b[12];node * root;int t;node *build(node *p,char v)  //建树{    if(p==NULL)    {        p=new node();        p->val=v;        return p;    }    if(v < p->val)        p->left=build(p->left,v);    else        p->right=build(p->right,v);    return p;}void pre(node *p,char *c)  //先序遍历{    if(p==NULL)        return ;    c[t++]=p->val;    pre(p->left,c);    pre(p->right,c);}int main(){    int n;    while(~scanf("%d",&n) && n)    {        scanf("%s",res);        root=new node();        root->val=res[0];        for(int i=1; i<strlen(res); i++)            build(root,res[i]);        t=0;        pre(root,a);        a[t]='\0';  //一定要加'\0'        while(n--)        {            scanf("%s",res);            root=new node();            root->val=res[0];            for(int i=1; i<strlen(res); i++)                build(root,res[i]);            t=0;            pre(root,b);            b[t]='\0';  //一定要加            if(!strcmp(a,b))                printf("YES\n");            else                printf("NO\n");        }    }    return 0;}

代码二:

#include<stdio.h>#include<string.h>#define N 1000int a[N],b[N];char res[10];void buildtree(int v,int *t){    int pos=1;    while(t[pos]!=-1)    {        if(t[pos]<v)            pos=pos*2+1;        else            pos=pos*2;    }    t[pos]=v;}int main(){    int n,flag;    while(~scanf("%d",&n) && n)    {        scanf("%s",res);        memset(a,-1,sizeof(a));        for(int i=0; i<strlen(res); i++)            buildtree(res[i]-'0',a);        while(n--)        {            memset(b,-1,sizeof(b));            flag=1;            scanf("%s",res);            for(int i=0; i<strlen(res); i++)                buildtree(res[i]-'0',b);            for(int i=0; i<N; i++)                if(a[i]!=b[i])                {                    flag=0;                    break;                }            if(flag)                printf("YES\n");            else                printf("NO\n");        }    }    return 0;}




原创粉丝点击