HDU3791:二叉搜索树

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 <cstring>
#include <cstdio>
#include <stdlib.h>
using namespace std;

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

typedef struct tree
{
    tree *l,*r;
    int num;
} tree;
tree *root;
tree *creat(int x)
{
    tree *t = (tree*)malloc(sizeof(tree));
    t->l = 0;
    t->r = 0;
    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->l = inster(s->l,x);
        else
            s->r = inster(s->r,x);
    }
    return s;
}

void libian(tree *root)
{
    if(root!=NULL)
    {
        b[cnt++] = root->num;
        libian(root->l);
        libian(root->r);
    }
}

int main()
{
    int n;
    while(cin >> n,n)
    {
        cnt = 0;
        root = NULL;
        int tem;
        char str[30];
        cin >> str;
        int len = strlen(str),i;
        for(i = 0; i<len; i++)
        {
            tem = str[i] - '0';
            root = inster(root,tem);
        }
        libian(root);
        for(i = 0; i<len; i++)
            a[i] = b[i];
        while(n--)
        {
            cnt = 0;
            cin >> str;
            root = NULL;
            for(i = 0; i<len; i++)
            {
                tem = str[i] - '0';
                root = inster(root,tem);
            }
            libian(root);
            for(i = 0; i<len; i++)
                if(a[i]!=b[i])
                {
                    cout << "NO" << endl;
                    break;
                }
            if(i>=len)
                cout << "YES" << endl;
        }
    }
    return 0;
}


 

 

posted @ 2013-04-02 21:56  坚固66  阅读(143)  评论(0编辑  收藏  举报