#include<iostream>
#include<stack> // 引入标准模板库stack头文件
using namespace std;
struct Tree
{
char data;
Tree* Lson;
Tree* Rson;
};
Tree* T;
// 输入一个二叉树
void creatTree(Tree* &tree)
{
char ch;
if ((ch = getchar()) == '#')
{
tree = NULL;
}
else
{
tree = new Tree;
tree->data = ch;
creatTree(tree->Lson);
creatTree(tree->Rson);
}
}
// 非递归前序遍历
void PreOrder_Nor1(Tree* tree)
{
if (tree == NULL)
return;
stack<Tree*>s; //创建一个空栈
while (tree != NULL || !s.empty())
{
while (tree != NULL)
{
cout << tree->data << " ";
s.push(tree);
tree = tree->Lson;
}
if (!s.empty())
{
tree = s.top();
tree = tree->Rson;
s.pop();
}
}
}
// 非递归中序遍历
void InOrder_Nor1(Tree* tree)
{
if (tree == NULL)
return;
stack<Tree*>s; //创建一个空栈
while (tree != NULL || !s.empty())
{
if (tree->Lson)
{
s.push(tree);
tree = tree->Lson;
}
else
{
cout << tree->data << " ";
tree = tree->Rson;
while (!tree && !s.empty())
{
tree = s.top();
cout << tree->data << " ";
s.pop();
tree = tree->Rson;
}
}
}
}
//非递归后序遍历
void PosOrder(Tree* tree)
{
if (tree == NULL)
return;
stack<Tree*>s; //创建一个空栈
Tree* pPre = NULL;
s.push(tree);
while (!s.empty())
{
tree = s.top();
if ((tree->Rson == NULL && tree->Rson == NULL) ||
(pPre != NULL && (tree->Lson == pPre || tree->Rson == pPre)))
{
cout << tree->data << " ";
pPre = tree;
s.pop();
}
else
{
if (tree->Rson != NULL)
s.push(tree->Rson);
if (tree->Lson != NULL)
s.push(tree->Lson);
}
}
}
int main()
{
cout << "输入一个二叉树(按照这个二叉树的前序遍历输入,若子节点为空就输入 # ):" << endl;
creatTree(T);
cout << "前序遍历:";
PreOrder_Nor1(T);
cout << endl;
cout << "中序遍历:";
InOrder_Nor1(T);
cout << endl;
cout << "后序遍历:";
PosOrder(T);
cout << endl;
delete T;
return 0;
}
//==感悟:栈内存放的是节点,push和pop的都是节点,tree != NULL是节点不为空 //
// tree->date是节点上的数字,所以不存在tree->data == NULL这种形式 //
// tree->Lson,tree->Rson是节点的左右儿子节点,不是这个节点的数字 //
如图:
输出结果: