二叉树按层遍历
2015-11-28 19:21
267 查看
这学期学数据结构,觉得写代码好麻烦,不过它让代码的结构改善很多,再难还是要学的.
![](http://static.blog.csdn.net/xheditor/xheditor_emot/default/smile.gif)
.对于二叉树,遍历方法有先序遍历,中序遍历,后续遍历,按层遍历.这里要讲的是按层遍历.有两种方法,第一种是递归,时间效率较低,另一种就是是充分运用了队列的性质,省去了了重复遍历的时间.(偷了个懒,,队列直接用了STL系列函数
![](http://static.blog.csdn.net/xheditor/xheditor_emot/default/tongue.gif)
)
代码如下:
![](http://static.blog.csdn.net/xheditor/xheditor_emot/default/smile.gif)
.对于二叉树,遍历方法有先序遍历,中序遍历,后续遍历,按层遍历.这里要讲的是按层遍历.有两种方法,第一种是递归,时间效率较低,另一种就是是充分运用了队列的性质,省去了了重复遍历的时间.(偷了个懒,,队列直接用了STL系列函数
![](http://static.blog.csdn.net/xheditor/xheditor_emot/default/tongue.gif)
)
代码如下:
#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; }
相关文章推荐
- 趣学Python-教孩子学编程--第四章
- 图片旋转
- MyEclipse 2014如何破解
- 二进制安装mysql5.5.32
- 一个很好用的Gif 图截取工具
- 中国R语言会议(上海会场)精彩视频 《数据科学的博客:从knitr到Jekyll》
- 再谈ArcGIS Runtime SDK for Android中文标注无法显示的问题
- 我的iOS学习历程 - UITabBarViewController
- 前台将xml转化成json的方法
- swift手动导入OC的第三方库
- 算法_php猴子选大王_约瑟夫问题
- fpm使用记录
- disable_functions php-fpm root
- ansible管理
- 论策略模式和状态模式
- IOS Xcode添加FrameWork
- hadoop学习004
- CCF认证考试(java)---窗口
- ansible管理
- visio绘制流程图-去掉默认的左侧栏(小例)