层次遍历二叉树,关键要用到队列,父结点一出,就要判断子结点是否为空,非空则马上进入队列
#include <iostream>
#include <queue>
using namespace std;
typedef struct bitnode
{
char data;
struct bitnode *lchild;
struct bitnode *rchild;
}bitnode,*bitree;
void create(bitree &bt)
{
char data;
cin>>data;
if(data=='#')
bt=NULL;
else
{
bt=(bitree)malloc(sizeof(bitnode));
bt->data=data;
create(bt->lchild);
create(bt->rchild);
}
}
int deep(bitree bt)
{
if(bt==NULL)
return 0;
else
{
int left=deep(bt->lchild);
int right=deep(bt->rchild);
if(left>=right)
return left+1;
else
return right+1;
}
}
void leveltraverse(bitree bt)
{
bitree b;
queue<bitree> q;
if(bt!=NULL)
q.push(bt);
while(!q.empty())
{
b=q.front();
cout<<b->data;
q.pop();
if(b->lchild!=NULL)
q.push(b->lchild);
if(b->rchild!=NULL)
q.push(b->rchild);
}
}
int main()
{
int level;
bitree bt;
create(bt);
level=deep(bt);
leveltraverse(bt);
}