二叉树层序遍历
思想很简单利用队列的操作,首先根结点入队,然后从队首出队元素并输出,随后将该结点的左右孩子分别入队,重复上述过程,直到左右孩子均为NULL
程序中用到的结构体和队列操作:
typedef struct Btnode
{
char data;
struct Btnode *lchild;
struct Btnode *rchild;
}BTNODE;
typedef struct Qnode
{
BTNODE *value;
struct Qnode *pNext;
}QNODE;
typedef struct Queue
{
QNODE *front;
QNODE *rear;
int qlength;
}QUEUE;
void En_Queue(QUEUE *,BTNODE *);
void Init_Queue(QUEUE *);
BTNODE *De_Queue(QUEUE *);
int QueueEmpty(QUEUE *);
void level_traverse(BTNODE *);
BTNODE *Creat_Binary_Tree(BTNODE *);
void En_Queue(QUEUE *q,BTNODE *p)
{
QNODE *pNew;
pNew = (QNODE *)malloc(sizeof(QNODE));
if(NULL==pNew)
{
printf("memory distribution error\n");
exit(-1);
}
pNew->value = p;
pNew->pNext = NULL;
if(q->qlength==0)
{
q->rear = pNew;
q->front = q->rear;
}
else
{
q->rear->pNext = pNew;
q->rear = pNew;
}
++(q->qlength);
}
void Init_Queue(QUEUE *q)
{
q->front = NULL;
q->rear = NULL;
q->qlength = 0;
}
BTNODE *De_Queue(QUEUE *q)
{
QNODE *p;
BTNODE *x;
if(q->qlength!=0)
{
p = q->front;
x = p->value;
q->front = p->pNext;
free(p);
--(q->qlength);
return x;
}
else
return NULL;
}
int QueueEmpty(QUEUE *q)
{
if(q->qlength==0)
return 1;
else
return 0;
}
层序遍历:
void level_traverse(BTNODE *root)
{
QUEUE q;
BTNODE *p;
p = root;
Init_Queue(&q);
En_Queue(&q,p);
while(!QueueEmpty(&q))
{
p = De_Queue(&q);
printf("%c",p->data);
if(p->lchild)
En_Queue(&q,p->lchild);
if(p->rchild)
En_Queue(&q,p->rchild);
}
}