zoukankan      html  css  js  c++  java
  • 二叉树——森林的带度数层次序列存储

    题目链接
    总时间限制: 1000ms 内存限制: 65536kB
    描述
    对于树和森林等非线性结构,我们往往需要将其序列化以便存储。有一种树的存储方式称为带度数的层次序列。我们可以通过层次遍历的方式将森林序列转化为多个带度数的层次序列。

    例如对于以下森林:
    img

    两棵树的层次遍历序列分别为:C E F G K H J / D X I

    每个结点对应的度数为:3 3 0 0 0 0 0 / 2 0 0

    我们将以上序列存储起来,就可以在以后的应用中恢复这个森林。在存储中,我们可以将第一棵树表示为C 3 E 3 F 0 G 0 K 0 H 0 J 0,第二棵树表示为D 2 X 0 I 0。

    现在有一些通过带度数的层次遍历序列存储的森林数据,为了能够对这些数据进行进一步处理,首先需要恢复他们。

    输入
    输入数据的第一行包括一个正整数n,表示森林中非空的树的数目。
    随后的 n 行,每行给出一棵树的带度数的层次序列。
    树的节点名称为A-Z的单个大写字母。
    输出
    输出包括一行,输出对应森林的后根遍历序列。
    样例输入

    2
    C 3 E 3 F 0 G 0 K 0 H 0 J 0
    D 2 X 0 I 0
    

    样例输出

    K H J E F G C X I D
    

    这道题,主要就是用队列存下根节点,根据其子节点数目判断是不是叶子。

    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <queue>
    using namespace std;
    
    typedef struct node{
        char data;
        struct node *child[26];
    }BitNode,*BitTree;
    
    void Init(BitTree &root, char ch){
        for(int i = 0;i < 26;i++){
            root->child[i] = NULL;
        }
        root->data = ch;
    }
    
    void Create(BitTree &root){
        queue <BitTree>qRoot;
        queue<int>qSeq;
        BitTree temp,tempHead;
        char ch;
        int i = 0;
        int degree = 0;//树的度
        int childNum;
        cin >> ch >> childNum;
        root = (BitTree)malloc(sizeof(BitNode));
        Init(root,ch);
        qRoot.push(root);
        qSeq.push(childNum);
        while(!qRoot.empty()){
            while(degree == i){
                if(qRoot.empty())
                    return ;
                degree = qSeq.front();
                qSeq.pop();
                tempHead = qRoot.front();
                qRoot.pop();
                i = 0;
            }
            cin >> ch >> childNum;
            temp = (BitTree)malloc(sizeof(BitNode));
            Init(temp,ch);
            qRoot.push(temp);
            qSeq.push(childNum);
            tempHead->child[i] = temp;
            i++;
        }
    }
    
    void AftTranverse(BitTree root){
        for(int i = 0;i < 26 && root->child[i];i++)
            AftTranverse(root->child[i]);
        cout << root->data << ' ';
    }
    
    int main(){
        //freopen("in.txt","r",stdin);
        BitTree root;
        int n;
        cin >> n;
        while(n--){
            Create(root);
            AftTranverse(root);
        }
        cout << '
    ';
        return 0;
    }
    
  • 相关阅读:
    python 函数的进阶
    python 函数的基础
    python3.6 中特殊格式化 和 字典中的pop
    python 文件操作
    python 基础数据类型补充,set集合,深浅拷贝
    python is 和 == 的区别,编码问题
    python字典
    python中堆和栈_Python小知识00002
    pip的更新_Python小知识00001
    Python字符串的编码
  • 原文地址:https://www.cnblogs.com/sean10/p/5010890.html
Copyright © 2011-2022 走看看