层次遍历算法

#include<bits/stdc++.h>

#define MaxSize 50

typedef struct node

{

 char data;

 struct node *lchild,*rchild;

}BTNode;

typedef struct

{

 BTNode *data[MaxSize];

 int front,rear;

}SqQueue;

void InitQueue(SqQueue *&q)

{

 q=(SqQueue *)malloc(sizeof(SqQueue));

 q->front=q->rear=-1;

}

void DestoryQueue(SqQueue *&q)

{

 free(q);

}

bool QueueEmpty(SqQueue *q)

{

 return (q->front==q->rear);

}

bool enQueue(SqQueue *&q,node *e)

{

 if(q->rear==MaxSize-1)

 {

  return false;

 }

 q->rear++;

 q->data[q->rear]=e;

 return true;

bool deQueue(SqQueue *&q,node *&e)

{

 if(q->front==q->rear)

 {

  return false;

 }

 q->front++;

 e=q->data[q->front];

 return true;

}

void Greate(BTNode *&T)

{

 char ch;

 scanf("%c",&ch);

 if(ch=='#') T=NULL;

 else 

 {

  T=(BTNode*)malloc(sizeof(BTNode));

  T->data=ch;

  Greate(T->lchild);

  Greate(T->rchild);

 }

}

void LevelOrder(BTNode *T)

{

 BTNode *p;

 SqQueue *qu;

 InitQueue(qu);

 enQueue(qu,T);

 while(!QueueEmpty(qu))

 {

  deQueue(qu,p);

  printf("%c",p->data);

  if(p->lchild!=NULL) enQueue(qu,p->lchild);

  if(p->rchild!=NULL) enQueue(qu,p->rchild);

 }

 DestoryQueue(qu);

}

int main()

{

 BTNode *T;

 Greate(T);

 LevelOrder(T);

 return 0;

}

猜你喜欢

转载自blog.csdn.net/2302_77099705/article/details/130910060