rt,直接贴代码了
#include <iostream>
#include <string>
#include <stack>
using namespace std;
typedef struct Node{
int value;
Node *left;
Node *right;
} Node;
void visit(Node *root){
cout<<(root->value)<<" ";
}
typedef struct Ele{
Node *n;
bool hasVR;
} Ele;
///
void preTrival_r(Node *root){
visit(root);
if(root->left)
preTrival_r(root->left);
if(root->right)
preTrival_r(root->right);
}
void midTrival_r(Node *root){
if(root->left)
midTrival_r(root->left);
visit(root);
if(root->right)
midTrival_r(root->right);
}
void postTrival_r(Node *root){
if(root->left)
postTrival_r(root->left);
if(root->right)
postTrival_r(root->right);
visit(root);
}
///
void preTrival(Node *root){
if(!root)
return;
stack<Node*> s;
s.push(root);
Node *cur = NULL;
while(!s.empty()){
cur=s.top();
s.pop();
visit(cur);
if(cur->right)
s.push(cur->right);
if(cur->left)
s.push(cur->left);
}
}
void midTrival(Node *root){
if(!root)
return;
stack<Node*> s;
Node *cur=root;
while( cur || !s.empty()){
if(cur){
s.push(cur);
cur = cur->left;
}
else{
cur = s.top();
s.pop();
visit(cur);
cur = cur->right;
}
}
}
void postTrival(Node *root){
if(!root)
return;
stack<Ele> s;
Node *cur=root;
while( cur || !s.empty()){
if(cur){
Ele e;
e.n = cur;
e.hasVR = false;
s.push(e);
cur = cur->left;
}
else{//start
Ele e = s.top();
s.pop();
if(!e.hasVR){
cur = e.n->right;
e.hasVR=true;
s.push(e);
}
else{
visit(e.n);
}
}//end
}
}
//
int main(){
Node r, l1, r1, l2, l3, l4, r4, r5;
r.value=1; l1.value=2; r1.value=3; l2.value=4; l3.value=5; l4.value=6; r4.value=7; r5.value=8;
r.left=&l1; r.right=&r1;
l1.left=&l2; l1.right=NULL;
l2.left=l2.right=NULL;
r1.left=&l3; r1.right=NULL;
l3.left=&l4; l3.right=&r4;
l4.left=l4.right=NULL;
r4.left=NULL; r4.right=&r5;
r5.left=r5.right=NULL;
//
// r 1
// / \ / \
// l1 r1 2 3
// / / / /
// l2 l3 4 5
// / \ / \
// l4 r4 6 7
// \ \
// r5 8
cout<<"preTrival:"<<endl;
preTrival_r(&r);
cout<<endl;
preTrival(&r);
cout<<endl<<endl;
cout<<"midTrival:"<<endl;
midTrival_r(&r);
cout<<endl;
midTrival(&r);
cout<<endl<<endl;
cout<<"postTrival:"<<endl;
postTrival_r(&r);
cout<<endl;
postTrival(&r);
cout<<endl<<endl;
return 0;
}