DS二叉树--层次遍历

题目描述

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

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

采用队列实现

输入

第一行输入一个整数t,表示有t个测试数据
第二行起输入二叉树先序遍历的结果,空树用字符‘0’表示,输入t行

输出

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

样例输入

2
AB0C00D00
ABCD00E000FG00H0I00

样例输出

ABDC
ABFCGHDEI

#include <iostream>
#include <queue>
using namespace std;

class Binary_tree_node
{
public:
    char data;                                //数据区域
    Binary_tree_node *LeftChild, *RightChild; //左右孩子
    Binary_tree_node() : LeftChild(NULL), RightChild(NULL) {}
    ~Binary_tree_node()
    {
        delete LeftChild;
        delete RightChild;
    }
};

class Binary_tree
{
public:
    Binary_tree_node *root; //根节点
    Binary_tree() {}
    ~Binary_tree() {}
    void CreateTree()
    {
        CreateTree(root);
    }
    void CreateTree(Binary_tree_node *&p)
    {
        char ch;
        cin >> ch;
        if (ch == '0')  //结点为空
        {
            p = NULL;
        }
        else            //结点不为空
        {
            p = new Binary_tree_node;
            p->data = ch;
            CreateTree(p->LeftChild);
            CreateTree(p->RightChild);
        }
    }

    void LevelOrder()
    {
        LevelOrder(root);
    }
    void LevelOrder(Binary_tree_node *p)
    {
        queue<Binary_tree_node *> tq;       //建立队列tq,队列的每个元素都是结点指针
        tq.push(p);
        if(root==NULL)      //树为空,直接返回
        {
            return ;
        }
        while (!tq.empty())
        {
            p = tq.front();
            tq.pop();
            cout << p->data;
            if (p->LeftChild!=NULL)
            {
                tq.push(p->LeftChild);
            }
            if (p->RightChild!=NULL)
            {
                tq.push(p->RightChild);
            }
        }
        cout << endl;
    }
};

int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        Binary_tree Bt;
        Bt.CreateTree();
        Bt.LevelOrder();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值