题目描述
层次遍历二叉树,是从根结点开始遍历,按层次次序“自上而下,从左至右”访问树中的各结点。
建树方法采用“先序遍历+空树用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();
}
}