层次遍历二叉树
2012-05-24 15:27:35 来源:WEB开发网核心提示:#include <stdio.h>#include<stdlib.h>typedef struct Bitree{int data;struct Bitree *Lchild,*Rchild;}BitreeNode,*LinkBitree;typedef struct QueueList{Li
#include <stdio.h> #include<stdlib.h> typedef struct Bitree { int data; struct Bitree *Lchild,*Rchild; }BitreeNode,*LinkBitree; typedef struct QueueList { LinkBitree data[20]; int front,rear; }QueueList,*LinkQueue; LinkBitree CreatBitree(); void LevelOrderTraverse(LinkBitree); void InitQueue(LinkQueue); int main() { LinkBitree BitreeHead; printf("请输入根结点的值e:"); BitreeHead=CreatBitree(); LevelOrderTraverse(BitreeHead); return 0; } LinkBitree CreatBitree() { int e_data; LinkBitree BitreeHead; scanf("%d",&e_data); if(e_data!=0) { BitreeHead=(LinkBitree)malloc(sizeof(BitreeNode)); if(BitreeHead==NULL) { printf("Error!!"); } else { BitreeHead->data=e_data; printf("请输入结点%d的左孩子结点的值:e= ",BitreeHead->data); BitreeHead->Lchild=CreatBitree(); printf("请输入结点%d的右孩子结点的值:e= ",BitreeHead->data); BitreeHead->Rchild=CreatBitree(); } } else { BitreeHead=NULL; } return BitreeHead; } void LevelOrderTraverse(LinkBitree BitreeHead) { LinkQueue Q; Q=(LinkQueue)malloc(sizeof(sizeof(QueueList))); InitQueue(Q); if(BitreeHead!=NULL) { Q->data[Q->rear]=BitreeHead; Q->rear=Q->rear+1; } while(Q->front!=Q->rear) { printf("%d ",Q->data[Q->front]->data); if(Q->data[Q->front]->Lchild!=NULL) { Q->data[Q->rear]=Q->data[Q->front]->Lchild; Q->rear=Q->rear+1; } if(Q->data[Q->front]->Rchild!=NULL) { Q->data[Q->rear]=Q->data[Q->front]->Rchild; Q->rear=Q->rear+1; } Q->front=Q->front+1; } } void InitQueue(LinkQueue Q) { Q->front=Q->rear=0; }