利用队列实现二叉树层次遍历
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <queue>
#include <stack>
#include <iostream>
using namespace std;
typedef struct BiTNode{
char data;
BiTNode *lchild, *rchild;
}BiTNode,*BiTree;
void CreateBiTree(BiTree &T)//建树
{
char ch;
scanf("%c",&ch);
if(ch==' ')
{
T=NULL;
return;
}
else
{
T=(BiTree)malloc(sizeof(BiTNode));
if(!T)
exit(1);
T->data=ch;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
void LevelOrderTraverse(BiTree T)//层次遍历
{
queue<BiTree> Queue;
if(!T)
{
printf("空树!\n");
return;
}
Queue.push(T);
while(!Queue.empty())
{
T=Queue.front();
Queue.pop();
printf("%c",T->data);
if(T->lchild)
Queue.push(T->lchild);
if(T->rchild)
Queue.push(T->rchild);
}
}
void main()
{
BiTree T;
CreateBiTree(T);
LevelOrderTraverse(T);
printf("\n");
}