【算法思想】
二叉树的层序遍历不同于其他三种遍历方式,并不是按照树的路径,而是根据树的层次来遍历的
因此很难通过递归的方式,但是层序遍历很像杨辉三角的构建,通过队列的方式将上层结点存储
在队列中,然后在输出队列中元素的同时。将输出元素的左右孩子加入队列。一次来达到层序输
出的效果。
【代码实现】
#include<iostream>
#include<queue>
using namespace std;
struct BinTree
{
char data;
struct BinTree *left ,*right ;
};
void levelOrderTraversal(BinTree *root)//层序遍历
{
if(root == NULL)return;
queue<BinTree*> res;
res.push(root);
while(!res.empty())
{
BinTree *temp;
temp = res.front();
res.pop();
cout<<temp->data<<' ';
if(temp->left){res.push(temp->left);}
if(temp->right){res.push(temp->right);}
}
}