您的位置:首页 > 其它

二叉树按层遍历

2015-11-28 19:21 267 查看
这学期学数据结构,觉得写代码好麻烦,不过它让代码的结构改善很多,再难还是要学的.

.对于二叉树,遍历方法有先序遍历,中序遍历,后续遍历,按层遍历.这里要讲的是按层遍历.有两种方法,第一种是递归,时间效率较低,另一种就是是充分运用了队列的性质,省去了了重复遍历的时间.(偷了个懒,,队列直接用了STL系列函数

)

代码如下:

#include<cstdio>
#include<iostream>
#include<queue>
using namespace std;
typedef struct Node{
char data;
struct Node *lchild;
struct Node *rchild;
}Node,*Bitree;
void Create(Bitree &T){
char ch;
cin>>ch;
if(ch!='#'){
T = new Node;
T->data = ch;
Create(T->lchild);
Create(T->rchild);
}
else T=NULL;
}
int Depth(Bitree T){
if(T){

int l=Depth(T->lchild);
int r=Depth(T->rchild);
return (l>r?l:r)+1;
}
else	return 0;

}
void dfs(Bitree T,int level){
if(T==NULL||level<1)
return;
if(level==1){
cout<<T->data<<" ";
return;
}
dfs(T->lchild,level-1);
dfs(T->rchild,level-1);

}
void floor(Bitree T){
int k=Depth(T);
for(int i=1;i<=k;i++){
dfs(T,i);
cout<<endl;
}
}
void qfloor(Bitree T){
queue<Bitree>q;
Bitree temp;
while(!q.empty()){
q.pop();
}
q.push(T);
while(!q.empty()){
temp=q.front();
q.pop();
cout<<temp->data <<" ";
if(temp->lchild)
{
q.push(temp->lchild );
}
if(temp->rchild )
{
q.push(temp->rchild );
}
}
cout<<endl;
}
int main(){
Bitree T;
cout<<"请输入树的先序序列: "<<endl;
Create(T);//T不为空树;
floor(T);//按层遍历,递归;
qfloor(T);//按层遍历的优化--队列;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: