EOJ1811 根据层号表示建树并后序遍历

光从前序表示,不能构造出唯一的树,但是加上了层号表示就可以了。下面是代码具体实现

#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <fstream>
#include <istream>
#include <ostream>
#include <complex>
#include <cstring>
#include <utility>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <string>
#include <cctype>
#include <ctime>
#include <cmath>
#include <queue>
#include <stack>
#include <list>
#include <new>
#include <set>
#include <map>

using namespace std;


const int maxn = 30;
const int INF = 0x3f3f3f3f;
struct Dnode
{
    char data;
    int level;
};
struct Node
{
    char data;
    int level;
    Node *child[maxn];
    Node *parent;
    Node(Dnode a)
    {
        data = a.data;
        level = a.level;
        for (int i=0; i<maxn; i++)
            child[i] = NULL;
        parent = NULL;
    }
};
Dnode a[maxn];

Node* build_tree(Dnode *a, int n)
{
    Node *root, *p, *q;
    if (n < 1) return NULL;
    root = new Node(a[0]);
    p = root;
    for (int i=1; i<n; i++)
    {
        q = new Node(a[i]);
        while (p->level >= q->level)
            p = p->parent;
        q->parent = p;
        int j = -1;
        while (p->child[++j] != NULL);
        p->child[j] = q;
        p = q;
    }
    return root;
}

void postorder(Node *root)
{
    if (root)
    {
        for (int i=0; i<maxn; i++)
        {
            if (root->child[i])
                postorder(root->child[i]);
            else break;
        }
        printf("%c", root->data);
    }
}

int main()
{

    //freopen("1.txt", "r", stdin);
    int n;
    scanf("%d", &n);
    getchar();
    for (int i=0; i<n; i++)
    {
        scanf("(%d,%c)", &a[i].level, &a[i].data);
        getchar();
    }
    Node *root = build_tree(a, n);
    postorder(root);
    putchar('\n');
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值