二叉树层次遍历(C语言)

输入样例:
1248009005003600700
0

输出样例:
123456789

在这里插入图片描述

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

#define MAX_SIZE 100
#define ElemType BiTree

typedef struct BiTNode {
    char data;
    struct BiTNode *left, *right;
} BiTNode, *BiTree;

typedef struct SqQueue {
    ElemType data[MAX_SIZE];
    int front, rear;
} SqQueue;


/*Binary Tree Part*/
void CreateBiTree(BiTree *T, char *str, int *cursor);

void DestroyBiTree(BiTree T);

void LevelOrderTraverseBiTree(BiTree T);

/*Sequence Queue Part*/
void InitQueue(SqQueue *Q);

bool IsEmptyQueue(SqQueue Q);

void EnQueue(SqQueue *Q, ElemType e);

void DeQueue(SqQueue *Q, ElemType *e);

int main() {
    char str[MAX_SIZE];
    while (scanf("%s", str) && str[0] != 48) {
        BiTree T = NULL;
        int cursor = 0;

        CreateBiTree(&T, str, &cursor);
        printf("\n");
        LevelOrderTraverseBiTree(T);
        DestroyBiTree(T);
    }

    return 0;
}

void CreateBiTree(BiTree *T, char *str, int *cursor) {
    if (str[*cursor] == 48) {
        *T = NULL;
    } else {
        *T = (BiTree) malloc(sizeof(BiTNode));
        (*T)->data = str[*cursor];

        (*cursor)++;
        CreateBiTree(&((*T)->left), str, cursor);
        (*cursor)++;
        CreateBiTree(&((*T)->right), str, cursor);
    }
}

void DestroyBiTree(BiTree T) {
    if (T) {
        DestroyBiTree(T->left);
        DestroyBiTree(T->right);
        free(T);
    }
}

void LevelOrderTraverseBiTree(BiTree T) {
    BiTree now_node;
    SqQueue Q;
    InitQueue(&Q);

    EnQueue(&Q, T);
    while (!IsEmptyQueue(Q)) {
        DeQueue(&Q, &now_node);
        printf("%c", now_node->data);

        if (now_node->left) {
            EnQueue(&Q, now_node->left);
        }
        if (now_node->right) {
            EnQueue(&Q, now_node->right);
        }
    }
}

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

bool IsEmptyQueue(SqQueue Q) {
    return (Q.front == Q.rear) ? true : false;
}

void EnQueue(SqQueue *Q, ElemType e) {
    if ((Q->rear + 1) % MAX_SIZE == Q->front) {
        printf("full\n");
        return;
    }
    Q->data[Q->rear] = e;
    Q->rear = (Q->rear + 1) % MAX_SIZE;
}

void DeQueue(SqQueue *Q, ElemType *e) {
    if (Q->rear == Q->front) {
        printf("empty\n");
        return;
    }
    *e = Q->data[Q->front];
    Q->front = (Q->front + 1) % MAX_SIZE;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值