#include <stdio.h> #include <stdlib.h> #define Maxsize 20
typedef char ElemType; struct Bitree { ElemType data; struct Bitree *l; struct Bitree *r; }; typedef struct Bitree TreeNode; typedef struct Bitree *BiTree; void LevelOrder(BiTree root) { BiTree ptr[Maxsize]; int rear = -1; int front = -1; if(root==NULL) return; else { rear = rear + 1; ptr[rear] = root; while(front!=rear) { front = front + 1; printf("%c\n",ptr[front]->data); if( ( ptr[front]->l ) != NULL ) { if( rear < (Maxsize-1)) { rear = rear + 1; ptr[rear] = ptr[front]->l; } else { printf("The queue is full\n"); } } if( ( ptr[front]->r ) != NULL ) { if( rear < (Maxsize-1)) { rear = rear + 1; ptr[rear] = ptr[front]->r; } else { printf("The queue is full\n"); } } } } }
BiTree CreateBiTree()//按先序次序输入二叉树中结点的值,'#'代表空树 { char e; BiTree tmp = NULL;
if( (e=getchar())!='#' ) { getchar();//接收回车符 tmp=(BiTree)malloc(sizeof(TreeNode)); if(!tmp) return NULL; tmp->data=e; printf("请输入左孩子:"); tmp->l=CreateBiTree(); printf("请输入右孩子:"); tmp->r=CreateBiTree(); } else getchar();//接收回车符
return tmp; }
void LevelOrder(BiTree root); BiTree CreateBiTree();
void main() { BiTree root = NULL; root = CreateBiTree(); LevelOrder(root); }