二叉搜索树(hdu3791)

二叉搜索树

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 2280    Accepted Submission(s): 994

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
 
思路很简单,建树,然后输出比较一下就好了,
对像我这种刚刚入门的还是有难度啊,,,,,
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

typedef struct tree
{
    tree *right,*left;
    int num;
}tree;
tree *root;

int a[30],b[30],count=0;

tree *creat(int x)//建树
{
    tree *t=(tree *)malloc(sizeof(tree));
    t->right=NULL;
    t->left=NULL;
    t->num=x;
    return t;
}

tree *inster(tree *s,int x)//插入
{
    tree *t;
    if(s==NULL)
    {
        t=creat(x);
        s=t;
    }
    else
    {
        if(x<=s->num)
            s->left=inster(s->left,x);
        else
            s->right=inster(s->right,x);
    }
    return s;
}
void libian(tree *root)
{
    if(root!=NULL)
    {
        b[count++]=root->num;
        libian(root->left);
        libian(root->right);
    }
}
int main()
{
    int n;
    while(scanf("%d",&n)>0&&n)
    {
        count=0;
        root=NULL;
        char str[30];
        scanf("%s",str);
        int len=strlen(str);
        int i,j;
        for(i=0;i<len;i++)
        {
            int tmp=str[i]-48;
            root=inster(root,tmp);
        }
        libian(root);
        for(i=0;i<len;i++)
            a[i]=b[i];
        while(n--)
        {
            count=i=0;
            scanf("%s",str);
            root=NULL;
            for(i=0;i<len;i++)
            {
                int tmp=str[i]-48;
                root=inster(root,tmp);
            }
            libian(root);
            for(i=0;i<len;i++)
                if(a[i]!=b[i])
                {
                    printf("NO
");
                    break;
                }
            if(i>=len)
                printf("YES
");
        }
    }
    return 0;
}


前几天放假,玩了几天,接下来继续学。。。。努力!

原文地址:https://www.cnblogs.com/yuyixingkong/p/3286077.html