二叉树的层次遍历
之前我已经讲解过了二叉树的先序遍历,中序遍历、后序遍历今天来看一个层次遍历,就以下面的树为例子吧,层次遍历就是一层一层的遍历,下图的层次遍历的结果是1,2,3,4,5,6,7那就看代码吧!
#include <iostream>
#include<queue>
using namespace std;
typedef struct BiTNode
{
int data;
struct BiTNode *lchild, *rchild; //左孩子 右孩子
}BiTNode, *BiTree;
void cengcibianli(BiTNode *T, queue<BiTNode*> &m_que)
{
if (T)
{
m_que.push(T);
}
BiTNode*temp{ nullptr };
while (!m_que.empty())
{
temp = m_que.front();
m_que.pop();
if (temp)
{
printf("%d ", temp->data);
m_que.push(temp->lchild);
m_que.push(temp->rchild);
}
}
}
void main()
{ /*
1
2 3
4 5 6 7
*/
BiTNode b1, b2, b3, b4, b5, b6, b7;
memset(&b1, 0, sizeof(BiTNode));
memset(&b2, 0, sizeof(BiTNode));
memset(&b3, 0, sizeof(BiTNode));
memset(&b4, 0, sizeof(BiTNode));
memset(&b5, 0, sizeof(BiTNode));
memset(&b6, 0, sizeof(BiTNode));
memset(&b7, 0, sizeof(BiTNode));
b1.data = 1;
b2.data = 2;
b3.data = 3;
b4.data = 4;
b5.data = 5;
b6.data = 6;
b7.data = 7;
//构建树关系
b1.lchild = &b2;
b1.rchild = &b3;
b2.lchild = &b4;
b2.rchild = &b5;
b3.lchild = &b6;
b3.rchild = &b7;
queue<BiTNode*> m_queue;
printf("\n层次遍历:\n");
cengcibianli(&b1, m_queue);
system("pause");
}
结果:
来源:CSDN
作者:HairLikeSnow
链接:https://blog.csdn.net/FairLikeSnow/article/details/104620679