问题 E: DS_6.5 层次遍历

时间限制: 15 Sec 内存限制: 128 MB
提交: 606 解决: 517

题目描述

从键盘接收扩展先序序列,以二叉链表作为存储结构,建立二叉树。输出这棵二叉树的层次遍历序列。

样例输入 Copy

ABC##DE#G##F###

样例输出 Copy

ABCDEFG

#include<stdio.h>
#include<stdlib.h>
#define MAX_SIZE 100
//节点类型定义
typedef struct Node{
    char data;
    struct Node* Lchild;
    struct Node* Rchild;
}BiTNode, *BiTree;

//定义队列
typedef struct{
    BiTNode node[MAX_SIZE];
    int front, rear;
}SeqQueue;

//初始化队列
 int InitQueue(SeqQueue *Q)
{
    //Q = (SeqQueue *)malloc(sizeof(SeqQueue));
    Q->front = Q->rear = -1;
}

//判空
int IsEmpty(SeqQueue *Q)
{
    if(Q->front == Q->rear)
        return 1;
    return 0;
}
//入队
int EnterQueue(SeqQueue *Q, BiTNode* p)
{
    if(Q->rear == MAX_SIZE-1)
        return 0;
    Q->rear++;
    Q->node[Q->rear] = *p;
    return 1;
}
//出队
int DeleteQueue(SeqQueue *Q, BiTNode* p)
{
    if(IsEmpty(Q))
    {
        return 0;
    }
    else
    {
        Q->front++;
        *p = Q->node[Q->front];
        return 1;
    }
}

//访问节点
/*void Visit(BiTNode p)
{
    printf("%c ", p.data);
}*/

//层次遍历二叉树
void LevelOrder(BiTree root)
{
    SeqQueue Q;
    BiTree p, q;
    InitQueue(&Q);
    EnterQueue(&Q, root);
    q = root;
    while(!IsEmpty(&Q))
    {
        p = q;
        DeleteQueue(&Q, p);
        printf("%c", p->data);
        if(p->Lchild != NULL)
        {
            EnterQueue(&Q, p->Lchild);
        }
        if(p->Rchild != NULL)
        {
            EnterQueue(&Q, p->Rchild);
        }
    }
}
//用扩展先序遍历建立二叉链表
void CreateBiTree(BiTree *root)
{
    char ch;
    ch = getchar();
    if(ch == '#')
        *root = NULL;
    else
    {
        (*root) = (BiTree)malloc(sizeof(BiTNode));
        (*root)->data = ch;
        CreateBiTree(&((*root)->Lchild));
        CreateBiTree(&((*root)->Rchild));
    }
}
int main()
{
    BiTree root = NULL;
    CreateBiTree(&root);
    LevelOrder(root);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值