#include <iostream>#include <stack>#include <map>#include <queue>#include <string.h>using namespace STD;structnode{CharData Node *left; Node *right; Node (CharD =Char()):d ATA (d), left (null), right (null) {}};classtree{ Public: Tree (): root (NULL) {}voidCreate (Char*LVR,Char*LRV) {intn =strlen(LRV); Create (Root,lvr,lrv,n); }voidPRINTFV ()//middle order{Node *t = root;if(T==null)return; Stack<Node*>St while(T!=null | | st.empty () = =false) { while(T!=null) {St.push (t); t=t->left; } t = St.top (); St.pop ();cout<<t->data<<" "; t=t->right; }cout<<endl; }voidPRINTFR ()// Post{Node *t = root;if(T==null)return; Stack<Node*>St map<node*,bool>mp//test visted, whether the record has been traversed. while(1) { while(T!=null && mp.find (t->left) ==mp.end ()) {St.push (t); t=t->left; } t = St.top ();if(T->right==null) {cout<<t->data<<" "; Mp.insert (pair<node*,BOOL> (T,true)); St.pop (); t = St.top ();Continue; }if(Mp.find (T->right) ==mp.end () &&t->right!=null) {//Whether the query already exists in the map, although inefficient, but intuitive. t=t->right;Continue; }if(Mp.find (St.top ()) ==mp.end ()) {cout<<st.top ()->data<<" "; Mp.insert (pair<node*,BOOL> (T,true)); St.pop ();if(St.size () >0) T = St.top (); }if(St.empty ()! =false) Break; }cout<<endl; }voidPRINTFL ()//Pre-order{Node *t = root;if(T==null)return; Stack<Node*>St while(T!=null | | st.empty () = =false) { while(T!=null) {cout<<t->data<<" "; St.push (t); t=t->left; } t = St.top (); St.pop (); t=t->right; }cout<<endl; }voidSprintf ()//Level{Node *t = root;if(T==null)return; queue<Node*>St St.push (t); while(St.empty () = =false) {Node *p = St.front ();cout<<p->data<<" "; St.pop ();if(P->left!=null) {St.push (p->left); }if(P->right!=null) {St.push (p->right); } }cout<<endl; }Private:voidCreate (Node *&t,Char*LVR,Char*LRV,intN) {//According to the sequence and post-order construction of two fork tree, with N records as the number of marks. if(n==0)return;inti =0; while(lrv[n-1]!=lvr[i]) i++; t =NewNode (lrv[n-1]); Create (t->right,lvr+i+1, lrv+i,n-i-1); Create (T->left,lvr,lrv,i); }Private: Node *root;};intMain () {Charlvr[]="Cbdafeg";Charlrv[]="Cdbfgea"; Tree T; T.create (LVR,LRV); T.PRINTFV (); T.PRINTFL (); T.PRINTFR (); T.sprintf ();return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Data structure: two fork tree (front, middle, post, hierarchy) non-recursive traversal.