之前讲过的中序遍历前序遍历、后序遍历,其中都是用的是递归来解决的,但我们的层序遍历它的特点是,先遍历第一层的,然后再遍历第二层的,依次下去,所以在这里我们想到的是队列,队列的特点是先进先出,所以我们运用对列来实现这个问题
#include<stdio.h>
#include<stdlib.h> //头文件
#include<assert.h>
#include<stdbool.h>
struct BinaryTreeNode;
typedef struct BinaryTreeNode* QDataType;
typedef struct QueueNode
{
QDataType data;
struct QueueNode* next;
}QueueNode;
typedef struct Queue
{
struct QueueNode*head;
struct QueueNode*tail;
}Queue;
void QueueInit(Queue*pq);
void QueueDestroy(Queue*pq);
void QueuePush(Queue*pq, QDataType X);
bool QueueEmpty(Queue*pq);
void QueuePop(Queue*pq);
QDataType QueueFront(Queue*pq);
QDataType QueueBack(Queue*pq);
#define _CRT_SECURE_NO_WARNINGS 1
#define _CRT_SECURE_NO_WARNINGS 1
#include"Queue.h"
void QueueInit(Queue*pq)//队列的初始化
{
assert(pq);
pq->head = NULL;
pq->tail = NULL;
}
void QueueDestroy(Queue*pq)//队列的销毁
{
assert(pq);
QueueNode*cur = pq->head;
while (cur)
{
QueueNode* next = cur->next;
free(cur);
cur = next;
}
pq->head = pq->tail = NULL;
}
void QueuePush(Queue*pq, QDataType X)//将数据加入对列中
{
assert(pq);
QueueNode*newnode = (QueueNode*)malloc(sizeof(QueueNode));
newnode->data = X;
newnode->next = NULL;
if (pq->head == NULL)
{
pq->head = pq->tail = newnode;
}
else
{
pq->tail->next = newnode;
pq->tail = newnode;
}
}
bool QueueEmpty(Queue*pq)//判断队列中还有没有数据
{
assert(pq);
return pq->head == NULL;
}
void QueuePop(Queue*pq)//删除队列的结点,从头开始删
{
assert(pq);
assert(!QueueEmpty(pq));
QueueNode*next = pq->head->next;
free(pq->head);
pq->head = next;
if (pq->head == NULL)
{
pq->tail = NULL;
}
}
QDataType QueueFront(Queue*pq)//得到队列前的数据
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->head->data;
}
QDataType QueueBack(Queue*pq)//得到队列后的数据
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->tail->data;
}
#define _CRT_SECURE_NO_WARNINGS 1
#include"Queue.h"
typedef int BTDataType;
typedef struct BinaryTreeNode//定义一个二叉树结构体
{
BTDataType data;
struct BinaryTreeNode* left;
struct BinaryTreeNode* right;
}BTNode;
BTNode*BuyNode(BTDataType x)//创建一个二叉树的结点
{
BTNode*newnode = (BTNode*)malloc(sizeof(BTNode));
if (newnode == NULL)
{
printf("malloc fail\n");
exit(-1);
}
newnode->data = x;
newnode->left = NULL;
newnode->right = NULL;
return newnode;
}
BTNode* CreatBinaryTree()//手动创造一个二叉树
{
BTNode* node1 = BuyNode(1);
BTNode* node2 = BuyNode(2);
BTNode* node3 = BuyNode(3);
BTNode* node4 = BuyNode(4);
BTNode* node5 = BuyNode(5);
BTNode* node6 = BuyNode(6);
node1->left = node2;
node1->right = node4;
node2->left = node3;
node4->left = node5;
node4->right = node6;
return node1;
}
void BinaryTreeLevelOrder(BTNode*root)//层序遍历的子程序
{
if (root == NULL)
{
return;
}
Queue q;
QueueInit(&q);
QueuePush(&q, root);
while (!QueueEmpty(&q))
{
BTNode*front = QueueFront(&q);
QueuePop(&q);
printf("%d ", front->data);
if (front->left != NULL)
{
QueuePush(&q, front->left);
}
if (front->right != NULL)
{
QueuePush(&q, front->right);
}
}
printf("\n");
QueueDestroy(&q);
}
int main()//主函数
{
BTNode*root = CreatBinaryTree();
BinaryTreeLevelOrder(root);
return 0;
}