資料結構-非遞迴實現後序遍歷二叉樹
阿新 • • 發佈:2019-02-04
最近在看關於樹結構方面的東西,想著實現二叉樹的遍歷操作。層序,先序,中序都還好,後序就比較麻煩,下面的地址很好的解釋了遞迴與非遞迴的實現方法,在此給出另一種非遞迴實現後序遍歷二叉樹的方法,通過複雜化資料結構,使得演算法更簡單。
http://blog.csdn.net/pi9nc/article/details/13008511
#include"iostream" #include "stack" using namespace std; #define N 7 typedef 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]; else p[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; }
程式親測可用。