层次遍历

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


//二叉树节点
typedef struct BitNode{
    int data;
    struct BitNode *lchild;
    struct BitNode *rchild;
}BitNode;

BitNode *CreateBitBitNode(void)
{
    BitNode *bt;
    int x;
    scanf("%d",&x);
    if(x==-1)bt=NULL;
    else{
        bt = (BitNode *)malloc(sizeof(BitNode));
        bt->data = x;
        bt->lchild = CreateBitBitNode();
        bt->rchild = CreateBitBitNode();
    }
    return bt;
}


//队列
typedef struct queue{
    struct node *pFront;
    struct node *pBehind;
    int size;
}Queue;

//普通节点
typedef struct node{
    struct BitNode * data;
    struct node * next;
}Node;


//队列初始化
Queue * init(){
    Queue * pQueue = (Queue *)malloc(sizeof(Queue));
    if(pQueue == NULL){
        printf("init queue failed!
");
        exit(0);
    }
    pQueue->pFront = NULL;
    pQueue->pBehind = NULL;
    pQueue->size = 0;
    return pQueue;
}
//判断队列是否为空
int empty(Queue * pQueue){
    if(pQueue->size == 0){
        return 1;
    }
    return 0;
}
//队列中添加数据
void in(Queue * pQueue, BitNode * pBitNode){
    Node * pNode = (Node *)malloc(sizeof(Node));
    if(pNode == NULL){
        printf("queue in data failed
");
        exit(0);
    }
    pNode->data = pBitNode;
    pNode->next = NULL;
    if(empty(pQueue)){
        pQueue->pFront = pNode;
    }else{
        pQueue->pBehind->next = pNode;
    }
    pQueue->pBehind = pNode;
    pQueue->size += 1;
}
//队列中移除并返回数据
BitNode * out(Queue * pQueue){
    if(empty(pQueue)){
        printf("queue is empty
");
        exit(0);
    }
    Node * pNode = pQueue->pFront;
    pQueue->pFront = pNode->next;
    pQueue->size -= 1;
    BitNode * pBitNode = pNode->data;
    free(pNode) ;
    pNode = NULL;
    return pBitNode;
}
BitNode * pop(Queue * pQueue){
    if(empty(pQueue)){
        printf("queue is empty!
");
        exit(0);
    }
    BitNode * pNode = pQueue->pBehind->data;
    return pNode;
}

//二叉树按层排印
void printLevel(BitNode * pRoot){
    if(pRoot == NULL){
        printf("binary BitNode is empty
");
        exit(0);
    }
    BitNode * pBitNode;
    Queue * pQueue = init();
    in(pQueue, pRoot);
    while(!empty(pQueue)){
        pBitNode = out(pQueue);
        printf("%d
", pBitNode->data);
        if(pBitNode->lchild != NULL){
            in(pQueue, pBitNode->lchild);
        }
        if(pBitNode->rchild != NULL){
            in(pQueue, pBitNode->rchild);
        }
    }
}

int main(){
    BitNode * pRoot = NULL;
    pRoot = CreateBitBitNode();
    printLevel(pRoot);

    return 0;
}
原文地址:https://www.cnblogs.com/minmsy/p/5317074.html