二叉樹的層序遍歷

我的主力博客:半畝方塘

層序遍歷二叉樹需要用到隊列的先進先出的特性,這裏的二叉樹採用二叉鏈接表示法,隊列是採用順序存儲結構的循環隊列,按照前序遍歷建立二叉樹,利用隊列層序遍歷二叉樹的主要過程如下:

  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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章