4.3二叉树的层次遍历王道数据结构例程实现

4.3二叉树的层次遍历王道数据结构例程实现

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

typedef int ElemType;

#define MaxSize 50

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

typedef struct{
    BiTree data[MaxSize];
    int front,rear;
} SqQueue;



void InitQueue(SqQueue &Q){
    Q.front=Q.rear=0;
}

bool IsEmpty(SqQueue Q){
    if(Q.front==Q.rear)
        return true;
    else
        return false;
}

bool EnQueue(SqQueue &Q,BiTree x){
    if((Q.rear+1)%MaxSize==Q.front)
        return false;
    Q.data[Q.rear]=x;
    Q.rear=(Q.rear+1)%MaxSize;
    return true;
}

bool DeQueue(SqQueue &Q,BiTree &x){
    if(Q.front==Q.rear)
        return false;
    x=Q.data[Q.front];
    Q.front=(Q.front+1)%MaxSize;
    return true;
}

BiTree CreateBiTree(BiTree &T){//利用先序遍历创建二叉树
    int x;
    printf("请输入下一个数字\n");
    scanf("%d",&x);
    if(x!=0){                   //等于0时跳过,所以该节点还为空
        T=(BiTree)malloc(sizeof(BiTNode));
        T->data=x;
        T->lchild=NULL;
        T->rchild=NULL;
        T->lchild=CreateBiTree(T->lchild);
        T->rchild=CreateBiTree(T->rchild);
    }
    return T;
}

void LevelOrder(BiTree T){
    SqQueue Q;
    InitQueue(Q);
    BiTree p;
    EnQueue(Q,T);
    while(!IsEmpty(Q)){
        DeQueue(Q,p);
        int a=p->data;
        printf(" %d",a);
        if(p->lchild!=NULL)
            EnQueue(Q,p->lchild);
        if(p->rchild!=NULL)
            EnQueue(Q,p->rchild);
    }
}

int main(){
    BiTree T;           //这是用先序遍历的方法创建的二叉树
	CreateBiTree(T);  //创建二叉树,124005003600700,每输入一个数字按一次回车
	printf("层次遍历输出\n");//例程是满二叉树,也可以自行实现。
	LevelOrder(T);
}

在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值