利用队列层次遍历二叉树

本文介绍了如何使用链队实现二叉树的层次遍历。首先定义了树节点和队列节点的结构体,接着提供了初始化链队、入队、出队和判断队列是否为空的函数。层次遍历函数通过将根节点入队,然后不断出队并检查其子节点是否非空来实现。最后,文章通过手动创建一个二叉树并进行层次遍历展示了整个过程。
摘要由CSDN通过智能技术生成

树形结构的层次遍历:

结构体定义:
typedef struct Tnode  //树节点
{
    int data;
    struct Tnode *lchil,*rchil;
}Tnode,*Tree;

typedef struct QNode // 队列节点
{
    Tnode* node;
    struct QNode *next;     
}QNode;

typedef struct link_queue //链队
{
    QNode *rear,*font;
}link_queue;
// 我们采取用重新定义一个结构体,里面放入两个QNode类型的指针来
遍历树节点函数:
// 遍历树节点
void printTree(Tree T){
    if(T!=NULL){
        printTree(T->lchil);
        printf("%d ",T->data);
        printTree(T->rchil);
    }    
}
链栈初始化:
// 初始化链栈
void InitQueue(link_queue *Q){
    Q->font = Q->rear = (QNode *)malloc(sizeof(QNode));
    Q->font->next = NULL;
}
入队操作:
// 入队
bool EnQueue(link_queue *Q,Tnode *e){
    QNode* p = (QNode *)malloc(sizeof(QNode));
    p->node = e;
    p->next = NULL;
    Q->rear->next = p;
    Q->rear = p;
    return true; 
}
出队操作:
// 出队列
bool DeQueue(link_queue *Q,Tnode **e){
    if(Q->font == Q->rear){
        return false;
    }
    QNode* p = Q->font->next;
    *e = p->node;
    Q->font->next = p->next;
    if(p->next == NULL){
        Q->rear = Q->font;
    }
    free(p);
    return true;
}
判断队空:
// 判断队列是否为空
bool emptyQueue(link_queue q){
    if(q.font == q.rear){
        return true;
    }
    return false;
}
树节点初始化创建:
// 创建节点
void createNode(Tnode *node, int e){
    node->data = e;
    node->lchil = node->rchil = NULL;
}
层次遍历函数主体:
// 层次遍历
void printLevel(Tree T){
    printf("中序遍历\n");
    printTree(T);
    printf("\n");
    // 创建队列
    Tnode **s,*p; // P为出队节点地址
    link_queue q;
    InitQueue(&q);
    // 跟节点入队
    EnQueue(&q,T);
    // 判断队列是否为空,不为空,就出队
    while (!emptyQueue(q))
    {
        // 队列不为空时
        DeQueue(&q,s);
        // 对出队元素进行判断是否有左右孩子,如果有则对左右孩子进行入队
        p = *s;
        printf("%d ",p->data);
        if(p->lchil != NULL){
            EnQueue(&q,p->lchil);
        } 
        if(p->rchil != NULL){
            EnQueue(&q,p->rchil);
        } 
    }
    printf("\n队列输出完成\n"); 
}
主函数:
  • 这里因为暂时还没学到用前序、中序队列创建二叉树,所以采用手动创建二叉树的方式
// 主函数
int main(){
    Tree T;
    T = (Tnode *)malloc(sizeof(Tnode));
    createNode(T,1);
    Tnode n1;
    Tnode n2;
    Tnode n3;
    Tnode n4;
    Tnode n5;
    Tnode n6;
    createNode(&n1,2);
    createNode(&n2,3);
    createNode(&n3,4);
    createNode(&n4,5);
    createNode(&n5,6);
    createNode(&n6,7);

    T->lchil = &n1;
    T->rchil = &n2;
    n1.lchil = &n6;
    n1.rchil = &n4;
    n2.rchil = &n5;
    n5.lchil = &n3;   
    printLevel(T);
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值