学完了二叉树的前中后序遍历(纵向的深度遍历),今天让我们看一下层序遍历,横向的广度遍历,下面这颗树的层序遍历,从左到右,结果为1,2,3,4,5。
有了前几个遍历的经验,我们想这个是否也需要其他数据结构辅助呢?假如我们先把1存起来,弹出打印1,再把2存起来,弹出打印2,再把3存起来,弹出打印3 … …
先存进去的先弹出来打印,后存进去的后弹出来打印,这与我们学过的哪个数据结构的特点比较像呢?QAQ,没错,就是队列,这次,我们舍弃了老朋友栈,邀请队列帮助我们!
首先定义初始化队列,首先将根1入队成为队首,弹出队首1打印,然后将队首1的非空左右入队,队里现在是2,3,队首是2,弹出2打印,2的非空左右入队,队里现在是3,4,5,队首是3,弹出3打印,非空左右入队,队里现在是4,5,队首是4,弹出4打印,非空左右入队,队里现在是5,队首是5,弹出5打印,非空左右入队。队里元素个数为0,结束。所以循环的条件就是队列里元素个数不为0,循环里的过程就是弹出队首,打印,队首的非空左右入队。同时在使用队列代码的时候不要忘记把队列里原来的数据类型,改成我们所需要的类型哦。
这里就把代码都给大家写出来了。可以参考一下
//二叉树的层序遍历(横向)(广度)
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int nVaule;
struct node *pRight;
struct node *pLeft;
}BinaryTree;
typedef struct data{
BinaryTree *Vaule;
struct data *pNext;
}MyQueue;
typedef struct queue{
MyQueue *pTop;
MyQueue *pTail;
int nCount;
}Queue;
BinaryTree *CreateBinarytree()
{
BinaryTree* pRoot = NULL;
//根
pRoot = (BinaryTree*)malloc(sizeof(BinaryTree));
pRoot->nVaule = 1;
//根的左
pRoot->pLeft = (BinaryTree*)malloc(sizeof(BinaryTree));
pRoot->pLeft->nVaule = 2;
//根的左的左
pRoot->pLeft->pLeft = (BinaryTree*)malloc(sizeof(BinaryTree));
pRoot->pLeft->pLeft->nVaule = 4;
pRoot->pLeft->pLeft->pLeft = NULL;
pRoot->pLeft->pLeft->pRight = NULL;
//根的左的右
pRoot->pLeft->pRight = (BinaryTree*)malloc(sizeof(BinaryTree));
pRoot->pLeft->pRight->nVaule = 5;
pRoot->pLeft->pRight->pLeft = NULL;
pRoot->pLeft->pRight->pRight = NULL;
//根的右
pRoot->pRight = (BinaryTree*)malloc(sizeof(BinaryTree));
pRoot->pRight->nVaule = 3;
pRoot->pRight->pLeft = NULL;
pRoot->pRight->pRight = NULL;
return pRoot;
}
void q_Init(Queue **pQueue)
{
*pQueue = (Queue*)malloc(sizeof(Queue));
(*pQueue)->pTop = NULL;
(*pQueue)->pTail = NULL;
(*pQueue)->nCount = 0;
}
void q_Push(Queue *pQueue,BinaryTree* nNum)
{
if(pQueue == NULL) exit(1);
MyQueue *pTemp = NULL;
pTemp = (MyQueue*)malloc(sizeof(MyQueue));
pTemp->Vaule = nNum;
pTemp->pNext = NULL;
if(pQueue->pTop == NULL)
{
pQueue->pTop = pTemp;
}
else
{
pQueue->pTail->pNext = pTemp;
}
pQueue->pTail = pTemp;
pQueue->nCount++;
}
BinaryTree* q_Pop(Queue *pQueue)
{
if(pQueue == NULL) exit(1);
if(pQueue->nCount == 0) return NULL;
MyQueue *pDel = pQueue->pTop;
BinaryTree* nNum = pDel->Vaule;
pQueue->pTop = pQueue->pTop->pNext;
free(pDel);
pDel = NULL;
pQueue->nCount--;
if(pQueue->nCount == 0)
{
pQueue->pTail = NULL;
}
return nNum;
}
void LevelTraversal(BinaryTree* pTree)
{
if(pTree == NULL) return;
//辅助队列
Queue *pQueue = NULL;
q_Init(&pQueue);
//遍历
//根入队
q_Push(pQueue,pTree);
while(pQueue->nCount>0)
{
//弹出
pTree = q_Pop(pQueue);
//打印
printf("%d ",pTree->nVaule);
//非空左右入队
if(pTree->pLeft !=NULL)
{
q_Push(pQueue,pTree->pLeft);
}
if(pTree->pRight != NULL)
{
q_Push(pQueue,pTree->pRight);
}
}
}
int main(){
BinaryTree *pTree = NULL;
pTree = CreateBinarytree();
LevelTraversal(pTree);
printf("\n");
return 0;
}