zoukankan      html  css  js  c++  java
  • DS二叉树--层次遍历

    题目描述

    层次遍历二叉树,是从根结点开始遍历,按层次次序“自上而下,从左至右”访问树中的各结点。

    建树方法采用“先序遍历+空树用0表示”的方法

    要求:采用队列对象实现,函数框架如下:

     

     输入

    第一行输入一个整数t,表示有t个测试数据

    第二行起输入二叉树先序遍历的结果,空树用字符‘0’表示,输入t行

    输出

    逐行输出每个二叉树的层次遍历结果

    样例输入

    2
    AB0C00D00
    ABCD00E000FG00H0I00

    样例输出

    ABDC
    ABFCGHDEI
    #include<iostream>
    #include<string>
    #include<queue>
    using namespace std;
    class BitreeNode
    {
    public:
        char data;
        BitreeNode *LeftChild, *RightChild;
        BitreeNode() :LeftChild(NULL), RightChild(NULL) {}
        ~BitreeNode() {}
    };
    class Bitree
    {
    private:
        BitreeNode *Root;
        int pos, sum;
        string strTree;
        void LevelOrder(BitreeNode *t)
        {
            queue<BitreeNode*> tq;
            BitreeNode *p = t;
            int x = 0;
            while (x < sum)
            {
                if (p)
                    tq.push(p);
                while (!tq.empty())
                {
                    p = tq.front();
                    tq.pop();
                    cout << p->data;
                    x++;
                    if (p->LeftChild)
                        tq.push(p->LeftChild);
                    if (p->RightChild)
                        tq.push(p->RightChild);
                }
            }
        }
        BitreeNode *CreateBitree()
        {
            BitreeNode *T;
            char ch;
            ch = strTree[pos++];
            if (ch == '0')
                T = NULL;
            else
            {
                sum++;
                T = new BitreeNode();
                T->data = ch;
                T->LeftChild = CreateBitree();
                T->RightChild = CreateBitree();
            }
            return T;
        }
    public:
        Bitree() {}
        ~Bitree(){}
        void CreateBitree(string TreeArray)
        {
            pos = 0;
            sum = 0;
            strTree.assign(TreeArray);
            Root = CreateBitree();
        }
        void LevelOrder()
        {
            LevelOrder(Root);
        }
    };
    
    int main()
    {
        int t;
        cin >> t;
        while (t--)
        {
            string str;
            cin >> str;
            Bitree *Tree;
            Tree = new Bitree();
            Tree->CreateBitree(str);
            Tree->LevelOrder();
            cout << endl;
        }
        return 0;
    }
  • 相关阅读:
    图像中的傅立叶变换(二)
    图像中的傅立叶变换(一)
    最大似然估计
    论文笔记:Batch Normalization
    TensorFlow学习笔记:共享变量
    postman管理收藏夹,批量执行接口
    postman设置token关联参数,其他接口直接读取token变量
    appium+python+unittest+HTMLRunner编写UI自动化测试集
    appium自动化环境搭建(python语言开发)
    Fiddler抓取https数据包
  • 原文地址:https://www.cnblogs.com/Liu269393/p/10223789.html
Copyright © 2011-2022 走看看