hdu 3999 The order of a Tree

先建立一颗二叉搜索树,然后先序遍历一下,就可以出答案了。

我用了比较奇葩的写法。。。二叉搜索树结构体模拟了一下。先序遍历用的DFS。。。。。。

#include<stdio.h>
#include<string.h>
struct abc{
    int left;
    int right;
    int date;
}node[100010];
int flag[100010];
int ans[100010];
int n, tot;
void dfs(int wei)
{
    if (node[wei].left != -1 && flag[node[wei].left] ==0)
    {
        flag[node[wei].left] = 1;
        ans[tot] = node[node[wei].left].date;
        tot++;
        dfs(node[wei].left);
    }
    if (node[wei].right != -1 && flag[node[wei].right] == 0)
    {
        flag[node[wei].right] = 1;
        ans[tot] = node[node[wei].right].date;
        tot++;
        dfs(node[wei].right);
    }
}
int main()
{
    int i,  k;
    while (~scanf("%d", &n))
    {
        memset(flag, 0, sizeof(flag));
        for (i = 0; i <= n; i++) node[i].date = -1, node[i].left = -1, node[i].right = -1;
        scanf("%d", &k);
        tot = 1;
        node[1].date = k;
        int nodesum = 2;
        for (i = 2; i <= n; i++)
        {
            scanf("%d", &k);
            int nodexun = 1;
            while (1)
            {
                if (k > node[nodexun].date)
                {
                    if (node[nodexun].right == -1)
                    {
                        node[nodexun].right = nodesum;
                        node[nodesum].date = k;
                        nodesum++;
                        break;
                    }
                    else nodexun = node[nodexun].right;
                }
                else
                {
                    if (node[nodexun].left == -1)
                    {
                        node[nodexun].left = nodesum;
                        node[nodesum].date = k;
                        nodesum++;
                        break;
                    }
                    else nodexun = node[nodexun].left;
                }
            }
        }
        ans[tot] = node[1].date;
        tot++;
        flag[1] = 1;
        dfs(1);
        for (i = 1; i <= n; i++)
        {
            if (i<n)
            printf("%d ", ans[i]);
            else printf("%d\n", ans[i]);
        }
    }
    return 0;
}

 

posted @ 2015-04-19 11:35  Fighting_Heart  阅读(139)  评论(0编辑  收藏  举报