参考博客:http://blog.csdn.net/cxllyg/article/details/7520037
#include <iostream>
#include <stack>
#include <queue>
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
using namespace std;
typedef struct BitNode{ //定义二叉树节点
char data;
BitNode* lchild;
BitNode* rchild;
}BitNode, *BiTree; //定义类型别名,和指向类型的指针类型别名
//创建二叉树
void CreatBiTree(BiTree &T) //传参时的引用????
{
char tmp;
cin >> tmp;
if (tmp == '#'){
T = NULL;
return;
}
else{
T = (BiTree)malloc(sizeof(BitNode));
T->data = tmp; //指针只能用->,变量可以用.表示
CreatBiTree(T->lchild);
CreatBiTree(T->rchild);
}
}
//递归遍历
//前序
void PreOrder(BiTree T)
{
if (T){
cout << T->data << endl;
//printf("%c", T->data);
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}
//中序
void MidOrder(BiTree T)
{
if (T){
MidOrder(T->lchild);
cout << T->data << endl;
MidOrder(T->rchild);
}
}
//后序
void PostOrder(BiTree T)
{
if (T){
PostOrder(T->lchild);
PostOrder(T->rchild);
cout << T->data << endl;
}
}
//非递归
//后序遍历 需要用到栈,和表示是否访问过某节点的右子树
void PostOrder2(BiTree T) //4个while
{
stack<BiTree> s; //存放树的节点
int flag[20]; //记录该节点的右子树是否被访问过
while (T){ //把左侧压入站,并标记未访问
s.push(T);
flag[s.size()] = 0;
T = T->lchild;
}
while (!s.empty()){ //引起一个循环
T = s.top();
while (T!=NULL&&T->rchild!=NULL && flag[s.size()] == 0){ //如果有右子树且未访问,就访问右子树,并标记为已访问
flag[s.size()] = 1;
T = T->rchild;
while (T){ //把右子树上所有左子树压入站,并标记未访问
s.push(T);
flag[s.size()] = 0;
T = T->lchild;
}
}
T = s.top(); //没有右子树,或是已经访问过的,输出
cout << T->data << endl;
s.pop(); //删除栈顶元素
}
}
void PostOrder4(BiTree T) //自己写的,感觉还可以2333
{
stack<BiTree> s;
int flag[20];
while (T || !s.empty()){
while (T){
s.push(T);
flag[s.size()] = 0;
T = T->lchild;
}
T = s.top();
if (T->rchild&&flag[s.size()] == 0){
flag[s.size()] = 1;
T = T->rchild;
}
else{
cout << T->data;
s.pop();
T = NULL;
}
}
}
void PostOrder3(BiTree T) //虹软的算法 2个while加if else
{
stack<BiTree> s;
BiTree pre_visited = NULL;
while (T || !s.empty()){
while (T){
s.push(T);
T = T->lchild;
}
T = s.top();
if (T->rchild == NULL || T->rchild == pre_visited){ //没有右子树,或是右子树已经访问过的,输出
cout << T->data << endl;
s.pop();
pre_visited = T;
T = NULL;
}
else{
T = T->rchild;
}
}
}
void PreOrder2(BiTree T)//前序非递归遍历
{
stack<BiTree> s;
while (T || !s.empty()){
while (T){
cout << T->data << endl;
s.push(T);
T = T->lchild;
}
T = s.top();
s.pop();
T = T->rchild;
}
}
void MidOrder2(BiTree T)//中序非递归遍历
{
stack<BiTree> s;
while (T || !s.empty()){
while (T){
s.push(T);
T = T->lchild;
}
T = s.top();
cout << T->data << endl;
s.pop();
T = T->rchild;
}
}
int main()
{
BiTree T;
CreatBiTree(T);
//PreOrder(T);
//MidOrder(T);
//PostOrder(T);
//PostOrder2(T);
PostOrder4(T);
//PostOrder3(T);
system("pause");
return 0;
}