栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c语言实现二叉树的层次遍历

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c语言实现二叉树的层次遍历

#二叉树

#Queue.h

//
// Created by Carry on 2021/10/26.
//

#ifndef EXAM_QUEUE_H
#define EXAM_QUEUE_H

#endif //EXAM_QUEUE_H

#define MaxSize 50
typedef BiTNode ElemType;
typedef struct {
    ElemType data[MaxSize];
    int front, rear;
} SqQueue;

typedef struct {
    ElemType data;
    struct linkNode *next;
} linkNode;

typedef struct {
    linkNode *front, *rear;
} linkQueue;




void InitQueue(linkQueue *Q) { //带头节点的链式队列
    Q->front = Q->rear = (linkNode *) malloc(sizeof(linkNode));
    Q->front->next = NULL;
}

int IsEmpty(linkQueue Q) {
    if (Q.front == Q.rear)return 1;
    else return 0;
}

void EnQueue(linkQueue *Q, ElemType x) {
    linkNode *s = (linkNode *) malloc(sizeof(linkNode));
    s->data = x;
    Q->rear->next = s;
    Q->rear = s;
}

int DeQueue(linkQueue *Q, ElemType *x) {
    if (Q->rear == Q->front) {
        return 0;
    }
    linkNode *p = Q->front->next;
    *x = p->data;
    Q->front->next = p->next;
    if (Q->rear == p) {
        Q->rear = Q->front;
    }
    free(p);
    return 1;
}

Tree.c

//
// Created by Carry on 2021/10/26.
//

#include "stdlib.h"
#include "stdio.h"

typedef int Elemtype;
typedef struct BiTNode {
    Elemtype data;
    struct BiTNode *lchild, *rchild;
} BiTNode, *BiTree;

#include "Queue.h"


void LevelOrder(BiTree T){
    linkQueue *L = (linkQueue *) malloc(sizeof (linkNode));
    InitQueue(L);
    BiTree p = (BiTree) malloc(sizeof (BiTNode));
    EnQueue(L,*T);
    while (!IsEmpty(*L)){
        DeQueue(L,p);
        printf("%d ",p->data);
        if(p->lchild){
            EnQueue(L,*p->lchild);
        }
        if (p->rchild) {
            EnQueue(L,*p->rchild);
        }
    }
}

int main() {
    BiTree node1 = (BiTree) malloc(sizeof(BiTNode));
    node1->data = 3;
    BiTNode node2;
    BiTNode node3;
    BiTNode node4;
    node2.data = 4;
    node3.data = 8;
    node4.data = 10;
    node1->lchild = &node2;
    node1->rchild = &node3;
    node2.lchild = &node4;
    node2.rchild = node3.lchild = node3.rchild = node4.rchild = node4.lchild = NULL;
    LevelOrder(node1);

    return 0;

}

#运行结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/1b5e76c6009f47ed850db04cd3e143a7.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBAQ2FycnlGbGFn,size_20,color_FFFFFF,t_70,g_se,x_16)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/353060.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号