数据结构-非递归实现后序遍历二叉树

来源:互联网 发布:高中信息技术编程基础 编辑:程序博客网 时间:2024/06/03 13:41

最近在看关于树结构方面的东西,想着实现二叉树的遍历操作。层序,先序,中序都还好,后序就比较麻烦,下面的地址很好的解释了递归与非递归的实现方法,在此给出另一种非递归实现后序遍历二叉树的方法,通过复杂化数据结构,使得算法更简单。

http://blog.csdn.net/pi9nc/article/details/13008511

#include"iostream"#include "stack"using namespace std;#define N 7typedef struct node{struct node* leftchild;struct node* rightchild;struct node* parent;int data;int flag;}BiTreeNode, *bt;BiTreeNode* CreateNode(int data){BiTreeNode* t=new BiTreeNode;t->data=data;t->leftchild=NULL;t->rightchild=NULL;t->flag=0;return t;}bt CreateBiTree(){bt p[N]={NULL};for(int i=0;i<N;i++){p[i]=CreateNode(i+1);}for(int i=0;i<N/2;i++){p[i]->leftchild=p[2*i+1];p[i]->rightchild=p[2*i+2];}for(int i=0;i<N;i++){if(i==0)p[i]->parent=NULL;else if(i%2==0)p[i]->parent=p[i/2-1];elsep[i]->parent=p[(i+1-1)/2];}return p[0];}int max(int a,int b){return a>b?a:b;}int depth(bt t){if(t==NULL)return 0;int nLeftDepth=depth(t->leftchild);int nRightDepth=depth(t->rightchild);return 1+max(nLeftDepth,nRightDepth);}//层序遍历void PrintNodeByOrder(bt b,int level){if(b==NULL || level<1)return;if(1 == level){cout<<b->data<<"  ";return;}PrintNodeByOrder(b->leftchild,level-1);PrintNodeByOrder(b->rightchild,level-1);}void LevelTraverse(bt b){int nHeight=depth(b);if(nHeight==0)cout<<"树为空"<<endl;for(int i=1;i<=nHeight;i++){PrintNodeByOrder(b,i);cout<<endl;}}//先序非递归遍历void PreTraverse(bt t){stack<bt>c;bt q=t;while(q!=NULL || !c.empty()){while(q!=NULL){cout<<q->data;c.push(q);q=q->leftchild;}if(!c.empty()){q=c.top();c.pop();q=q->rightchild;}}}//中序非递归遍历void InTraverse(bt t){stack<bt>c;bt q=t;while(q!=NULL || !c.empty()){while(q!=NULL){c.push(q);q=q->leftchild;}if(!c.empty()){q=c.top();cout<<q->data;c.pop();q=q->rightchild;}}}//后序非递归遍历void PostOrder(bt t){bt m=t;while(m!=NULL){switch(m->flag){case 0:{m->flag=1;if(m->leftchild!=NULL)m=m->leftchild;break;}case 1:{m->flag=2;if(m->rightchild!=NULL)m=m->rightchild;break;}case 2:{m->flag=0;cout<<m->data;m=m->parent;break;}}}}int main(){BiTreeNode* p=CreateBiTree();cout<<"层次遍历"<<endl;LevelTraverse(p);cout<<endl;cout<<"先序非递归遍历"<<endl;PreTraverse(p);cout<<endl;cout<<"中序非递归遍历"<<endl;InTraverse(p);cout<<endl;cout<<"后序非递归遍历"<<endl;PostOrder(p);cout<<endl;return 0;}

程序亲测可用。

阅读全文
0 0