#include<iostream>
#include<stack>
using namespace std;
struct node{
int val;
struct node* left;
struct node* right;
bool is_first;
node(int x):val(x),left(NULL),right(NULL),is_first(true){
}
};
void pre(node* head)
{
if (head!=NULL)
{
cout<<head->val<<" ";
pre(head->left);
pre(head->right);
}
}
void pre2(node* head)
{
stack<node* >s;
node* p = head;
while (p!=nullptr || !s.empty()) //注意初始条件。 ||
{
while (p!=nullptr)
{
cout<<p->val<<" "; //1、访问
s.push(p); //2、入栈
p = p->left; // 左
}
if (!s.empty())
{
p = s.top(); //将当前节点扔掉,因为以及访问过,而且其左孩子为空。
s.pop();
p = p->right; // 右
}
}
}
void in_order(node* head)
{
if (head)
{
in_order(head->left);
cout<<head->val<<" ";
in_order(head->right);
}
}
void in_order2(node* head)
{
node* p = head;
stack<node* >s;
while (p!=nullptr || !s.empty())
{
while(p!=nullptr)
{
s.push(p);
p = p->left;
}
if (!s.empty())
{
p = s.top();
cout<<p->val<<" ";
s.pop();
p = p->right;
}
}
}
void post_order(node* head)
{
if(head)
{
post_order(head->left);
post_order(head->right);
cout<<head->val<<" ";
}
}
void post_order2(node* head)
{
node* p = head;
stack<node* >s;
while (p!=nullptr || !s.empty())
{
while (p!=nullptr)
{
s.push(p);
p = p->left;
}
if (!s.empty())
{
p = s.top();
s.pop();
if (!(p->is_first)) //第二次出现
{
cout<<p->val<<" ";
p = NULL;
}
else
{
p->is_first = false;
s.push(p); // 第一次出现的化,再次压入,确保右孩子为 NULL
p = p->right;
}
}
}
}
int main()
{
struct node* p = new node(1);
p->left = new node(2); p->left->left = new node(4); p->left->left->right = new node(6);
p->left->left->right->left = new node(7); p->left->left->right->right = new node(8);
p->right = new node(3); p->right->right = new node(5);
// pre(p);
// pre2(p);
// in_order(p);
// in_order2(p);
// post_order(p);
post_order2(p);
return 0;
}
参考:https://www.cnblogs.com/dolphin0520/archive/2011/08/25/2153720.html
https://www.jianshu.com/p/456af5480cee