环境:VS2008
BinaryTreeTraver.h
#ifndef BINARY_TREE_TRAVER_H
#define BINARY_TREE_TRAVER_H
#include <iostream>
#include <stack>
using namespace std;
//node of the tree
typedef struct Node{
int mValue;
Node* left;
Node* rigth;
}TreeNode;
//前序遍历
void PreOrder(Node* h);
//另外一种前序遍历
void PreOrder_Ex(Node* h);
//中序遍历
void InOrder(Node* h);
//另外一种中序遍历
void InOrder_Ex(Node* h);
//后序遍历
void PostOrder(Node* h);
#endif
BinaryTreeTraver.cpp
#include "BinaryTreeTraver.h"
//前序遍历
void PreOrder(Node* h){
Node* p = h;
stack<Node *> n_Stack;
while(p || !n_Stack.empty()){
if(p){
n_Stack.push(p);
cout<<p->mValue<<" ";
p = p->left;
}
else{
p = n_Stack.top()->rigth;
n_Stack.pop();
}
}
}
void PreOrder_Ex(Node* h){
if(h == NULL)
return;
Node* p = h;
stack<Node*> n_Stack;
//顶点入栈
n_Stack.push(p);
while(!n_Stack.empty()){
p = n_Stack.top();//取栈顶元素
n_Stack.pop();//栈顶元素出栈
if(p != NULL){
cout<<p->mValue<<" ";
//两个孩子分别入栈,注意入栈顺序
n_Stack.push(p->rigth);
n_Stack.push(p->left);
}
}
}
//中序遍历
void InOrder(Node* h){
Node* p = h;
stack<Node*> n_Stack;
while(p || !n_Stack.empty()){
if(p){
n_Stack.push(p);
p = p->left;
}
else{
p = n_Stack.top();
cout<<p->mValue<<" ";
n_Stack.pop();
p = p->rigth;
}
}
}
//another inorder
void InOrder_Ex(Node* h){
Node* p = h;
stack<Node*> n_Stack;
while(p || !n_Stack.empty()){
//向左到底
while(p){
n_Stack.push(p);
p = p->left;
}
p = n_Stack.top();
cout<<p->mValue<<" ";
n_Stack.pop();
p = p->rigth;
}
}
//后序遍历
void PostOrder(Node* h){
Node* p = h;
Node* pre = NULL;
stack<Node *> n_Stack;
while(p || !n_Stack.empty()){
if(p){
n_Stack.push(p);
p = p->left;
}
else{
p = n_Stack.top();
if(p->rigth == NULL || p->rigth == pre){//如果p没有右孩子或者右孩子已经被访问了,就访问p
cout<<p->mValue<<" ";
n_Stack.pop();
pre = p;
p = NULL;//注意这里要对p赋空值,下一个p是栈顶元素,不然程序会陷入死循环
}
else{//先访问右孩子
p = p->rigth;
}
}
}
}
main.cpp
#include "BinaryTreeTraver.h"
int main(){
Node* n1 = (Node*)malloc(sizeof(Node));
Node* n2 = (Node*)malloc(sizeof(Node));
Node* n3 = (Node*)malloc(sizeof(Node));
Node* n4 = (Node*)malloc(sizeof(Node));
Node* n5 = (Node*)malloc(sizeof(Node));
n1->mValue = 1;
n2->mValue = 2;
n3->mValue = 3;
n4->mValue = 4;
n5->mValue = 5;
n1->left = n2;
n1->rigth = n3;
n2->left = n4;
n2->rigth = 0;
n3->left = 0;
n3->rigth = 0;
n4->left = n5;
n4->rigth = 0;
n5->left = 0;
n5->rigth = 0;
cout<<"PreOrder:\n";
PreOrder(n1);
cout<<"\nPreOrder_Ex:\n";
PreOrder_Ex(n1);
cout<<"\nInOder:\n";
InOrder_Ex(n1);
cout<<"\nPostOrder:\n";
PostOrder(n1);
system("pause");
return 0;
}