#include <iostream>
#include <stack>
#include <vector>
#include <string>
using namespace std;
class BTNode
{
public:
int val;
BTNode* left;
BTNode* right;
BTNode(int x): val(x), left(NULL), right(NULL)
{}
};
//二叉树的非递归遍历
//前序遍历
void PreNonRecur(BTNode* root)
{
if (!root)
{
return ;
}
BTNode* p = root;
stack<BTNode*> s;
while (!s.empty() || p)
{
//p不空,遍历左子树,进栈
while (p)
{
cout << p->val << " ";
s.push(p);
p = p->left;
}
//p为空,出栈
if (!s.empty())
{
p = s.top();
s.pop();
p = p->right;
}
}
cout << endl;
}
//中序遍历
void MidNonRecur(BTNode* root)
{
if (!root)
{
return ;
}
BTNode* p = root;
stack<BTNode*> s;
while (!s.empty() || p)
{
//p不空,遍历左子树,进栈
while (p)
{
s.push(p);
p = p->left;
}
//p为空,出栈
if (!s.empty())
{
p = s.top();
s.pop();
cout << p->val << " ";
p = p->right;
}
}
cout << endl;
}
//后序遍历
void LastNonRecur(BTNode* root)
{
if (!root)
{
return;
}
BTNode* pCur = root;
BTNode* pLastVisit = NULL;
stack<BTNode*> s;
while (pCur)
{
s.push(pCur);
pCur = pCur->left;
}
while (!s.empty())
{
pCur = s.top();
s.pop();
if (!pCur->right || pCur->right == pLastVisit)
{
cout << pCur->val << " ";
pLastVisit = pCur;
}
else
{
s.push(pCur);
pCur = pCur->right;
while (pCur)
{
s.push(pCur);
pCur = pCur->left;
}
}
}
cout << endl;
}
int main()
{
BTNode a(1);
BTNode b(2);
BTNode c(3);
BTNode d(4);
BTNode e(5);
BTNode f(6);
a.left = &b;
a.right = &c;
b.left = &d;
b.right = &e;
e.right = &f;
PreNonRecur(&a);
system("pause");
return 0;
}