层次遍历C语言

题目描述
编一个程序,读入用户输入的一串先序遍历字符串,根据输入建立一棵二叉树, 并输出该二叉树的层次遍历序列。层次遍历是指逐层访问,每一层又按从左到右的次序访问结点。
输入
输入包括1行字符串,长度不超过100。
输出
输出二叉树的层次遍历序列。每个结点先输出一个空格,然后再跟着输出结点的数据。
样例输入 Copy
12##3##
样例输出 Copy
1 2 3

#include <iostream>
#include <cstdio>
#include <malloc.h>
using namespace std;
#define MAXSIZE 100

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

typedef struct SQueue
{
    BiTree data[MAXSIZE];
    int front,rear;
}SQueue,*Queue;

BiTree creatTree(BiTree T)
{
    char ch;
    T=(BiTree)malloc(sizeof(BiTNode));
    scanf("%c",&ch);
    if(ch=='#') return 0;
    T->data=ch;
    T->lchild=creatTree(T->lchild);
    T->rchild=creatTree(T->rchild);
    return T;
}

void InitQueue(Queue Q)
{
    Q -> front = Q -> rear = 0;
}

int IsEmptyQueue(Queue Q)
{
    return Q -> rear == Q -> front?1:0;
}

void EnQueue(BiTree T,Queue Q)
{
    if((Q -> rear+1) % MAXSIZE == Q -> front)
    {
        printf("Queue is fulled!\n");
        return  ;
    }
    Q->rear=(Q->rear+1)%MAXSIZE;
    Q->data[Q->rear]=T;
}

BiTree Gethead(Queue Q)
{
    if(IsEmptyQueue(Q)) return 0;
    BiTree T;
    T=Q ->data[(Q ->front+1) % MAXSIZE];
    Q ->front=(Q ->front+1) % MAXSIZE;
    return T;
}

void LevelOrder(BiTree T)//层次遍历 
{
    SQueue Q ;
    BiTree S ;
    if(!T) return ;
    InitQueue(&Q);
    EnQueue(T,&Q);
    while(!IsEmptyQueue(&Q))
    {
        S=Gethead(&Q);
        printf(" %c",S->data);
        if(S->lchild!=NULL) EnQueue(S->lchild,&Q);
        if(S->rchild!=NULL) EnQueue(S->rchild,&Q);
    }
}

int main()
{
    BiTree tree;
    tree=creatTree(tree);
    LevelOrder(tree);
    return 0;
}
  • 7
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Shuo..

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

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

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

打赏作者

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

抵扣说明:

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

余额充值