Post Order比较难以理解,开辟的lastVisited记录上次访问的点,如果这个点是当前点的右孩子,则打印当前点
#include <iostream>
#include <stack>
struct node
{
int data;
node* left;
node* right;
node(int exData)
{
data = exData;
left = NULL;
right = NULL;
}
};
void dfs(node* root)
{
std::stack<node*> st;
node* cur = root;
while(cur || !st.empty())
{
while(cur)
{
st.push(cur);
std::cout << cur->data << " ";
cur = cur->left;
}
if(!st.empty())
{
cur = st.top();
cur = cur->right;
st.pop();
}
}
};
void postOrderTrav(node *root)
{
std::stack<node*> st;
node* cur = root;
node* lastVisited = NULL;
node* p = NULL;
while(cur || !st.empty())
{
while(cur)
{
st.push(cur);
cur = cur->left;
}
p = st.top();
if(!p->right || p->right == lastVisited)
{
std::cout << p->data << " ";
lastVisited = p;
st.pop();
}
else
{
cur = p