数据结构——二叉树进行层次遍历使用链队列

题目描述:(使用链队列进行操作)

从键盘输入一个字符串,其中#表示空。

例:右图输入为

Sample Input

HDB#A##C##G#FE###

使用队列将二叉树分层输出。

Sample Output

HDGBCFAE

思路:

  1. 根节点入队,然后:
     
  2. 从队列中取出一个元素
     
  3. 访问该元素所指的结点
     
  4. 若该元素所指结点的左、右孩子结点非空,则将其左、右孩子的指针顺序入队

代码如下:

//c语言实现二叉树层次遍历(借助队列实现)
#include <stdio.h>
#include <stdlib.h>

//二叉链表类型定义
typedef struct btnode
{
    char data;
    struct btnode *lchild,*rchild;
}bitree,*Bitree;


//链队列类型定义
typedef struct LinkQueueNode
{
    bitree *data;
    struct LinkQueueNode *next;
}LKQueNode;


typedef struct LKQueue
{
    LKQueNode *front,*rear;
}LKQue;


//初始化队列
void InitQueue(LKQue *LQ)
{
    LKQueNode *p;
    p = (LKQueNode*)malloc(sizeof(LKQueNode));
    LQ->front = p;
    LQ->rear = p;
    LQ->front->next = NULL;
}


//判断队列是否为空
int EmptyQueue(LKQue *LQ)
{
    if(LQ->front == LQ->rear)
        return 1;
    else
        return 0;
}


//入队列
void EnQueue(LKQue *LQ,Bitree x)
{
    LKQueNode *p;
    p = (LKQueNode*)malloc(sizeof(LKQueNode));
    p->data = x;
    p->next = NULL;
    LQ->rear->next = p;
    LQ->rear = p;
}


//出队列
int OutQueue(LKQue *LQ)
{
    LKQueNode *s;
    if ( EmptyQueue(LQ))
    {
        exit(0);
        return 0;
    }
    else
    {
        s = LQ->front->next;
        LQ->front->next = s->next;
        if(s->next == NULL)
        LQ->rear = LQ->front;
        free(s);
        return 1;
    }
}


//取队列首元素
Bitree GetHead(LKQue *LQ)
{
    LKQueNode *p;
    bitree *q;
    if(EmptyQueue(LQ))
    return q;
    else
    {
        p = LQ->front->next;
        return p->data;
    }
}


//建二叉树
Bitree Initiate()
{
    char ch;
    Bitree t;
    ch = getchar();
    if(ch == '#')
        t = NULL;
    else
    {
        t = (Bitree)malloc(sizeof(bitree));
        t->data = ch;
        t->lchild = Initiate();
        t->rchild = Initiate();
    }
    return t;
}

//层次遍历
void LevelOrder(Bitree bt)
{
    LKQue Q;
    Bitree p;
    InitQueue(&Q);
    if(bt != NULL)
    {
        EnQueue(&Q,bt);
        while(!EmptyQueue(&Q))
        {
            p = GetHead(&Q);
            OutQueue(&Q);
            printf("%c",p->data); //输出是char
            if(p->lchild != NULL)
                EnQueue(&Q,p->lchild);
            if(p->rchild != NULL)
                EnQueue(&Q,p->rchild);
        }
    }
}


int main()
{
    Bitree T;
    printf("按先序序列输入结点序列,'#'代表空:\n");
    T=Initiate();
    printf("\n层次遍历序列为:");
    LevelOrder(T);
    printf("\n");
    return 0;
}

 

  • 7
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李逍遥~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值