二叉树的层序遍历

我的主力博客:半亩方塘

层序遍历二叉树需要用到队列的先进先出的特性,这里的二叉树采用二叉链接表示法,队列是采用顺序存储结构的循环队列,按照前序遍历建立二叉树,利用队列层序遍历二叉树的主要过程如下:

  1. 将二叉树的根结点的指针入队列
  2. 若队列非空,将队列中的队头元素出队列,然后将该队头元素的左孩子指针(若存在)入队列,接着将队头元素的右孩子指针(若存在)入队列
  3. 重复过程2,直到队列中没有元素为止

具体代码实现过程如下:

/**
 * 用队列作为辅助手段层序遍历二叉树
 * author: 王小平
 * date: 2015/12/04
 */

#include <stdio.h>
#include <stdlib.h>

/* 二叉链表表示的二叉树 */
typedef char TElemType;
typedef struct BiTNode   /* 结点结构 */
{
    TElemType data;
    struct BiTNode *lchild, *rchild;
} BiTNode, *BiTree;

/* 前序遍历建立二叉树 */
void PreCreateBiTree(BiTree *T)
{
    TElemType ch;
    scanf("%c", &ch);

    if('#' == ch)
        *T = NULL;
    else {
        *T = (BiTree)malloc(sizeof(BiTNode));
        (*T)->data = ch;
        PreCreateBiTree(&((*T)->lchild));
        PreCreateBiTree(&((*T)->rchild));
    }
}

/* 顺序循环队列 */
#define MAXSIZE 100
typedef BiTree QElemType;
typedef struct
{
    QElemType data[MAXSIZE];
    int front, rear;     // 分别存放队头和队尾的位置
} SqQueue, *SqQueuePtr;

/* 初始化队列 */
void InitQueue(SqQueuePtr Q)
{
    Q->front = 0;
    Q->rear = 0;
}

/* 判断队列空 */
int QEmpty(SqQueuePtr Q)
{
    return (Q->front == Q->rear);
}

/* 判断队列满 */
int QFull(SqQueuePtr Q)
{
    return ((Q->rear + 1) % MAXSIZE == Q->front);
}

/* 从队尾入队列 */
typedef int Status;
#define OK 1
#define ERROR 0
Status EnQueue(SqQueuePtr Q, QElemType e)
{
    if(QFull(Q))   /* 队列满则返回错误 */
        return ERROR;

    Q->data[Q->rear++] = e;
    return OK;
}

/* 从队头出队列 */
Status DeQueue(SqQueuePtr Q, QElemType *e)
{
    if(QEmpty(Q))
        return ERROR;   /* 队列空则返回错误 */

    *e = Q->data[Q->front++];
    return OK;
}

/* 层序遍历二叉树 */
void LevelTraverse(BiTree T)
{
    SqQueuePtr queue;
    queue = (SqQueuePtr)malloc(sizeof(SqQueue));
    InitQueue(queue);

    /* 1、将二叉树的根结点入队列
     * 2、将队头元素出队列
     * 3、并将队头元素的左子树的根结点(非空)右子树的根结点(非空)分别入队列
     * 4、重复2、3,直至队列中没有元素
     */
    EnQueue(queue, T);
    QElemType tmp;
    while(!QEmpty(queue)) {
        DeQueue(queue, &tmp);
        printf("%3c", tmp->data);
        if(tmp->lchild)
            EnQueue(queue, tmp->lchild);
        if(tmp->rchild)
            EnQueue(queue, tmp->rchild);
    }
    printf("\n");
}

int main()
{
    BiTree tree;
    printf("Please input a binary tree:\n");
    PreCreateBiTree(&tree);

    printf("The result of level traverse:\n");
    LevelTraverse(tree);

    return 0;
}


有关源代码以及运行截图请移步至我的github

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值