二叉树层次遍历算法——C/C++

二叉树层次遍历

层次遍历基础需要了解二叉树、队列。
二叉树基本运算:https://blog.csdn.net/weixin_42109012/article/details/92000919
顺序队基本运算:https://blog.csdn.net/weixin_42109012/article/details/92104948

1. 算法思想

用一个队列保存被访问的当前节点的左右孩子以实现层次遍历。
在进行层次遍历的时候,设置一个队列结构,遍历从二叉树的根节点开始,首先将根节点指针入队列,然后从队头取出一个元素,每取一个元素,执行下面两个操作:

  1. 访问该元素所指向的节点
  2. 若该元素所指节点的左右孩子节点非空,则将该元素所指节点的左孩子指针和右孩子指针顺序入队。此过程不断进行,当队列为空时,二叉树的层次遍历结束。

2. 原理解释

2.1. 二叉树图

一个二叉树,层次遍历就是每一行每一行的取出数据。
这个图的结果就是 ABCDEFGH
在这里插入图片描述

2.2. 层次遍历过程图

就是先父节点进入队列,然后循环,出队时带入下一组子节点进队,没有就没有进入队列的,当队列为空时结束循环。
在这里插入图片描述

3. 代码实现

3.1 实现步骤

1、首先将二叉树的根节点进入队列中,判断队列不为NULL。
2、打印输出该节点存储的元素。
3、判断节点如果有孩子(左孩子、右孩子),就将孩子进入队列中。
4、循环以上操作,直到 BT->lchild == NULL、BT->rchild=NULL。

3.2 全部代码

#define _CRT_SECURE_NO_WARNINGS // VS忽略警告,其它应该不需要

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

#define MAX_SIZE 128
#define STR_SIZE 1024

typedef struct Node {    // 定义二叉链
    char         data;   // 数据元素
    struct Node* lchild; // 指向左孩子节点
    struct Node* rchild; // 指向右孩子节点
} BTNode;                // struct Node 的别名

typedef struct Quene {      // 定义顺序队
    int     front;          // 队头指针
    int     rear;           // 队尾指针
    BTNode* data[MAX_SIZE]; // 存放队中元素
} SqQueue;                  // struct Queue 的别名

/**
 * 队列函数
 */
void initQueue(SqQueue** q);             // 初始化队列
bool emptyQueue(SqQueue* q);             // 判断队列空
bool enQueue(SqQueue* q, BTNode* node);  // 入队
bool deQueue(SqQueue* q, BTNode** node); // 出队

/**
 * 二叉树函数
 */
// void createBTNode2(BTNode** BT);                  // 创建二叉树
int  createBTNode(BTNode** BT, char* str, int n); // 创建二叉树
void preOrder(BTNode* BT);                        // 前序遍历
void inOrder(BTNode* BT);                         // 中序遍历
void postOrder(BTNode* BT);                       // 后序遍历
void levelOrder(BTNode* BT);                      // 层次遍历

/**
 * 画树函数
 */
void draw_level(BTNode* node, bool left, char* str); // 画分支
void draw(BTNode* root);                             // 画根节点

/***************************************************************************
 * @date    2019/12/08
 * @brief   层次遍历二叉树
 * @param   BT  二叉树根节点
 ***************************************************************************/
void levelOrder(BTNode* BT) {
    SqQueue* q;       // 定义队列
    initQueue(&q);    // 初始化队列
    if (BT != NULL) { // 根节点指针进队列
        enQueue(q, BT);
    }
    // 一层一层的把节点存入队列,当没有孩子节点时就不再循环
    while (!emptyQueue(q)) {      // 队不为空循环
        deQueue(q, &BT);          // 出队时的节点
        printf("%c", BT->data);   // 输出节点存储的值
        if (BT->lchild != NULL) { // 有左孩子时将该节点进队列
            enQueue(q, BT->lchild);
        }
        if (BT->rchild != NULL) { // 有右孩子时将该节点进队列
            enQueue(q, BT->rchild);
        }
    }
}

int main() {
    // 例子:ABDH###E##CF##G##
    BTNode* BT;
    printf("请输入字符串:");
    char* str = (char*)malloc(sizeof(char) * STR_SIZE);
    scanf("%s", str);
    if (strlen(str) == createBTNode(&BT, str, 0)) {
        printf("二叉树建立成功\n");
    }
    // printf("请输入字符串:");
    // createBTNode2(&BT);
    // draw(BT);

    printf("\n先序遍历结果:");
    preOrder(BT);

    printf("\n中序遍历结果:");
    inOrder(BT);

    printf("\n后序遍历结果:");
    postOrder(BT);

    printf("\n层序遍历结果:");
    levelOrder(BT);

    return 0;
}

// 初始化队列
void initQueue(SqQueue** q) {
    if (!((*q) = (SqQueue*)malloc(sizeof(SqQueue)))) {
        printf("内存分配失败!");
        exit(-1);
    }
    (*q)->front = (*q)->rear = -1; // 置 -1
}

// 判断队列是否为空
bool emptyQueue(SqQueue* q) {
    // 首指针和尾指针相等,说明为空。空-返回真,不空-返回假
    if (q->front == q->rear) {
        return true;
    }
    return false;
}

// 进队列
bool enQueue(SqQueue* q, BTNode* node) {
    // 判断队列是否满了。满(插入失败)-返回假,不满(插入成功)-返回真
    if (q->rear == MAX_SIZE - 1) {
        return false;
    }
    q->rear++;               // 头指针加 1
    q->data[q->rear] = node; // 传值
    return true;
}

// 出队列
bool deQueue(SqQueue* q, BTNode** node) {
    // 判断是否空了。空(取出失败)-返回假,不空(取出成功)-返回真
    if (q->front == q->rear) {
        return false;
    }
    q->front++;                // 尾指针加 1
    *node = q->data[q->front]; // 取值
    return true;
}

// 创建二叉树
int createBTNode(BTNode** BT, char* str, int n) {
    char ch = str[n++];  // 把第 n 个字符赋给ch,方便后面判断,字符下标后移
    if (ch != '\0') {    // 如果 ch 不等于结束符就继续创建,否则就结束
        if (ch == '#') { // 以 # 号代表 NULL,下面没有了
            *BT = NULL;
        } else {
            if (!(*BT = (BTNode*)malloc(sizeof(BTNode)))) {
                printf("内存分配失败!");
                exit(-1);
            } else {
                (*BT)->data = ch;
                n           = createBTNode(&((*BT)->lchild), str, n); // 左递归创建
                n           = createBTNode(&((*BT)->rchild), str, n); // 右递归创建
            }
        }
    }
    // 返回 n,记录字符串使用到哪里了
    return n;
}
// 创建二叉树
// void createBTNode2(BTNode** BT) {
//     char ch;
//     ch = getchar();
//     if (ch == '#') {
//         *BT = NULL;
//     } else {
//         if (!(*BT = (BTNode*)malloc(sizeof(BTNode)))) {
//             printf("内存分配失败!");
//             return;
//         } else {
//             (*BT)->data = ch;
//             createBTNode2(&((*BT)->lchild)); // 分配成功则接着建立左子树和右子树
//             createBTNode2(&((*BT)->rchild));
//         }
//     }
// }

// 先序遍历
void preOrder(BTNode* BT) {
    if (BT != NULL) {           // 判断不为空
        printf("%c", BT->data); // 访问根节点
        preOrder(BT->lchild);   // 递归,先序遍历左子树
        preOrder(BT->rchild);   // 递归,先序遍历右子树
    }
}

// 中序遍历
void inOrder(BTNode* BT) {
    if (BT != NULL) {
        inOrder(BT->lchild);
        printf("%c", BT->data);
        inOrder(BT->rchild);
    }
}

// 后序遍历
void postOrder(BTNode* BT) {
    if (BT != NULL) {
        postOrder(BT->lchild);
        postOrder(BT->rchild);
        printf("%c", BT->data);
    }
}

/*****************************************************************************
* @date   2020/4/19
* @brief  水平画树
* @param  node	二叉树节点
* @param  left	判断左右
* @param  str 	可变字符串
*****************************************************************************/
void draw_level(BTNode* node, bool left, char* str) {
    if (node->rchild) {
        draw_level(node->rchild, false, strcat(str, (left ? "|     " : "      ")));
    }

    printf("%s", str);
    printf("%c", (left ? '\\' : '/'));
    printf("-----");
    printf("%c\n", node->data);

    if (node->lchild) {
        draw_level(node->lchild, true, strcat(str, (left ? "      " : "|     ")));
    }
    //  "      " : "|     " 长度为 6
    str[strlen(str) - 6] = '\0';
}

/*****************************************************************************
* @date   2020/4/19
* @brief  根节点画树
* @param  root	二叉树根节点
*****************************************************************************/
void draw(BTNode* root) {
    char str[STR_SIZE];
    memset(str, '\0', STR_SIZE);

    /**
     * 1. 在 windows 下,下面是可执行的
     * 2. 在 Linux   下,执行会报 Segmentation fault
     *      需要使用中间变量
     */
    if (root->rchild) {
        draw_level(root->rchild, false, str);
    }
    printf("%c\n", root->data);
    if (root->lchild) {
        draw_level(root->lchild, true, str);
    }
}

4. 结果展示

创建二叉树是以 “#” 为结束符NULL。
例子就是最上面的图:ABDH###E##CF##G##
结果应该为:ABCDEFGH
在这里插入图片描述

  • 363
    点赞
  • 1387
    收藏
    觉得还不错? 一键收藏
  • 31
    评论
以下是C语言实现二叉树层次遍历算法的示例代码: ```c #include <stdio.h> #include <stdlib.h> // 二叉树结点结构体 typedef struct node { int data; // 结点数据 struct node *left; // 左子树结点指针 struct node *right; // 右子树结点指针 } Node, *Tree; // 队列结构体 typedef struct queue { Tree data; // 队列元素数据 struct queue *next; // 下一个队列元素指针 } Queue, *Stack; // 初始化队列 void initQueue(Queue **queue) { *queue = (Queue *) malloc(sizeof(Queue)); (*queue)->next = NULL; } // 判断队列是否为空 int isQueueEmpty(Queue *queue) { return (queue->next == NULL); } // 入队 void enqueue(Queue *queue, Tree data) { Queue *newNode = (Queue *) malloc(sizeof(Queue)); newNode->data = data; newNode->next = NULL; Queue *p = queue; while (p->next != NULL) { p = p->next; } p->next = newNode; } // 出队 Tree dequeue(Queue *queue) { Queue *p = queue->next; Tree data = p->data; queue->next = p->next; free(p); return data; } // 二叉树层次遍历 void levelOrderTraversal(Tree tree) { if (!tree) { return; } Queue *queue; initQueue(&queue); enqueue(queue, tree); while (!isQueueEmpty(queue)) { Tree node = dequeue(queue); printf("%d ", node->data); if (node->left) { enqueue(queue, node->left); } if (node->right) { enqueue(queue, node->right); } } } // 测试代码 int main() { // 构造二叉树 Tree tree = (Tree) malloc(sizeof(Node)); tree->data = 1; tree->left = (Tree) malloc(sizeof(Node)); tree->left->data = 2; tree->left->left = NULL; tree->left->right = NULL; tree->right = (Tree) malloc(sizeof(Node)); tree->right->data = 3; tree->right->left = NULL; tree->right->right = NULL; tree->left->left = (Tree) malloc(sizeof(Node)); tree->left->left->data = 4; tree->left->left->left = NULL; tree->left->left->right = NULL; tree->right->right = (Tree) malloc(sizeof(Node)); tree->right->right->data = 5; tree->right->right->left = NULL; tree->right->right->right = NULL; // 层次遍历 levelOrderTraversal(tree); return 0; } ``` 以上是一个基于队列实现的二叉树层次遍历算法的 C 语言示例代码。在该示例代码中,主要包括了初始化队列、判断队列是否为空、入队、出队等队列操作函数,以及二叉树层次遍历函数 levelOrderTraversal。在 levelOrderTraversal 函数中,我们首先将根节点入队,然后进行循环遍历,每次出队一个结点,并将该结点的左右子树入队,直到队列为空为止,期间找到的各个结点就是二叉树层次遍历结果。
评论 31
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值