您的位置:首页 > 职场人生

July 微软面试100题 第16题 二叉树的层次遍历

2011-04-25 21:42 746 查看
输入一颗二叉树,从上往下按层次打印树的每个节点,同一层中按照从左往右的顺序打印。

二叉树的层次遍历,用队列非常容易实现。

这里用的是链队列。

程序清单如下:

#include <iostream.h>
#include <malloc.h>
typedef struct TNode
{
int data;
struct TNode *lchild;
struct TNode *rchild;
}*Tree;
typedef struct QNode
{
TNode t;
struct QNode *next;
}*QuePtr;//队列节点
typedef struct LinkQue
{
QuePtr front;
QuePtr rear;
}*LinkQuePtr;//队列
int InitQue(LinkQue &Q)
{
Q.front=Q.rear=(QuePtr)malloc(sizeof(QNode));
if(!Q.front)
{
cout<<"初始化队列失败!"<<endl;
return 0;
}
Q.front->next=NULL;
return 1;
}//队列的初始化
int EnQueue(LinkQue &Q,TNode *t)
{
if(t==NULL)
return 0;
QuePtr q;
q=(QNode *)malloc(sizeof(QNode));
q->next=NULL;
q->t=*t;
Q.rear->next=q;
Q.rear=q;
return 1;
}//入队操作
TNode DeQueue(LinkQue &Q)
{
if(Q.front==Q.rear)
{
cout<<"队列为空!"<<endl;
}
else
{
QuePtr q;
q=(QuePtr)malloc(sizeof(QNode));
q=Q.front->next;
Q.front->next=q->next;
if(Q.front->next==NULL)
Q.rear=Q.front;
return q->t;
}
}//出队操作
int QueueEmpty(LinkQue Q)
{
if(Q.front==Q.rear)
return 1;
else
return 0;
}//判断队列是否为空
void CreateTree(Tree &T)
{
int t;
cin>>t;
if(t==0)
T=NULL;
else
{
T=(TNode *)malloc(sizeof(TNode));
T->data=t;
CreateTree(T->lchild);
CreateTree(T->rchild);
}
}//递归的建立二叉树
void HierTree(Tree T)
{
LinkQue Q;
InitQue(Q);
EnQueue(Q,T);
TNode *t=(TNode *)malloc(sizeof(TNode));
while(!QueueEmpty(Q))
{
*t=DeQueue(Q);
cout<<(*t).data<<endl;
EnQueue(Q,(*t).lchild);
EnQueue(Q,(*t).rchild);
}
}
void main()
{
Tree T;
cout<<"请按照先序序列输入一棵二叉树(空节点用0表示):"<<endl;
CreateTree(T);
cout<<"此树的层次遍历为:"<<endl;
HierTree(T);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: