广度优先周游二叉树

主要思想:
从根结点开始逐层逐个地访问各个结点。在周游开始的时候,首先把根结点放入队列;
然后每次从队列中取出队头元素进行处理,每处理一个结点时,按从左到右的顺序把它的所有子结点放入对列。

#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 20
#define OK 1
#define ERROR 0

typedef int Status;
typedef char TElemType;

//二叉树的链式储存结构
typedef struct BiTNode
{
    TElemType data;
    struct BiTNode * lchild;
    struct BiTNode * rchild;
}BiTNode,*BiTree;

typedef BiTree QElemtype;
//循环队列的储存结构
typedef struct
{
    QElemtype data[MAXSIZE];
    int front;
    int rear;
}sqQueue;

//队列的初始化
Status InitQueue(sqQueue * Q)
{
    Q->front=0;
    Q->rear=0;
    return OK;
}

//队列长度
Status QueueLength(sqQueue Q)
{
    return (Q.rear-Q.front+MAXSIZE)%MAXSIZE;
}

//入队操作
Status EnQueue(sqQueue * Q, QElemtype e)
{
    if((Q->rear+1)%MAXSIZE==Q->front)
    {
        return ERROR;
    }
    Q->data[Q->rear]=e;
    Q->rear=(Q->rear+1)%MAXSIZE;
    return OK;
}


//出队操作
Status DeQueue(sqQueue * Q,QElemtype * e)
{
    if(Q->front==Q->rear)
    {
        return ERROR;
    }
    *e=Q->data[Q->front];
    Q->front=(Q->front+1)%MAXSIZE;
    return OK;
}


//二叉树的建立
void CreateBiTree(BiTree * T)
{
    TElemType ch;
    scanf("%c",&ch);
    if(ch=='#')
    {
        *T=NULL;
    }
    else
    {
        *T=(BiTree)malloc(sizeof(BiTNode));
    }
    if(!*T)
    {
        return ;
    }
    else
    {
        (*T)->data=ch;
        CreateBiTree(&(*T)->lchild);    //构造左子树
        CreateBiTree(&(*T)->rchild);    //构造右子树
    }
}


//广度优先周游二叉树(层次遍历)
void LevelOrder(BiTree * T,sqQueue * Q)
{
    if(*T)
    {
        EnQueue(Q,(*T));
    }
    while(QueueLength((*Q))!=0)
    {
        DeQueue(Q,&(*T));
        printf("%c ",(*T)->data);   //访问当前结点
        if((*T)->lchild!=NULL)
        {
            EnQueue(Q,(*T)->lchild);
        }
        if((*T)->rchild!=NULL)
        {
            EnQueue(Q,(*T)->rchild);
        }
    }
    printf("\n");
}


int main()
{
    sqQueue Q;
    BiTree root;
    InitQueue(&Q);
    printf("please enter the data:\n");
    CreateBiTree(&root);
    printf("LevelOrdertraversal the data:\n");
    LevelOrder(&root,&Q);
    return 0;
}

运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值