题目描述
层次遍历二叉树,是从根结点开始遍历,按层次次序“自上而下,从左至右”访问树中的各结点。
建树方法采用“先序遍历+空树用0表示”的方法
建议使用队列结构实现,算法框架如下:
定义一个空白队列和一个树结点指针p
设T是指向根结点的指针变量,若二叉树为空,则返回;否则,令p=T,p入队,执行以下循环:
(1)队首元素出队到p;
(2)访问p所指向的结点;
(3)p所指向的结点的左、右子结点依次入队。
(4)跳转步骤1循环,直到队列空为止
例如把上述算法中的访问操作定义为输出,算法结果就是把二叉树按层次遍历输出
输入
第一行输入一个整数t,表示有t个测试数据
第二行起输入二叉树先序遍历的结果,空树用字符‘0’表示,输入t行
输出
逐行输出每个二叉树的层次遍历结果
AC代码:
#include <iostream>
#include <queue>
//#include "math.h"
#include "algorithm"
#include "stack"
#include "iomanip"
using namespace std;
int mmax=1000;
queue<char> child;
queue<char> parents;
class node{
public:
char data;
node *left= nullptr;
node *right= nullptr;
node *parent = nullptr;
};
queue<node*> q;
node* Create(string str,int& index){
if(str[index]=='0'){
return nullptr;
}
node* tmp=new node;
tmp->data=str[index];
tmp->left= Create(str,++index);
tmp->right= Create(str,++index);
if(tmp->left)
tmp->left->parent=tmp;
if(tmp->right)
tmp->right->parent=tmp;
return tmp;
}
void cengci(node *root){
if(!root)
return;
while(!q.empty()){
if(root->left)
q.push(root->left);
if(root->right)
q.push(root->right);
cout<<q.front()->data;
q.pop();
cengci(q.front());
}
;
}
int main() {
int t;
cin>>t;
while(t--){
string str;
cin>>str;
int index=0;
node* root = Create(str,index);
q.push(root);
cengci(root);
while (!q.empty()){
cout<<q.front();
q.pop();
}
cout<<endl;
}