二叉树按层遍历

来源:互联网 发布:matlab迭代算法 编辑:程序博客网 时间:2024/06/06 02:35

这学期学数据结构,觉得写代码好麻烦,不过它让代码的结构改善很多,再难还是要学的.微笑.对于二叉树,遍历方法有先序遍历,中序遍历,后续遍历,按层遍历.这里要讲的是按层遍历.有两种方法,第一种是递归,时间效率较低,另一种就是是充分运用了队列的性质,省去了了重复遍历的时间.(偷了个懒,,队列直接用了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;}elsereturn 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;}


0 0
原创粉丝点击