/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> result;
if(root==NULL) return result;
TreeNode *pre= root;
stack<TreeNode*> s;
s.push(root);
TreeNode *prev = NULL;
while (!s.empty()) {
TreeNode *curr = s.top();
if (!prev || prev->left == curr || prev->right == curr) {
if (curr->left)// try to visit the left node;
s.push(curr->left);
else if (curr->right)// if left node is empty ; push the right child
s.push(curr->right);
} else if (curr->left == prev) {
if (curr->right)
s.push(curr->right);
} else {
//cout << curr->data << " ";
result.push_back(curr->val);
s.pop();
}
prev = curr;
}
}
};
Some code can push your code to the end; so do not forget them;
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> result;
if(root==NULL) return result;
TreeNode *pre= NULL;
stack<TreeNode *> stk;
stk.push(root);
while(!stk.empty())
{
TreeNode *cur = stk.top();
if(pre==NULL || pre->left == cur || pre->right == cur)
{// if the pre is the father of cur;means the whole visit has just done;we should go down to the deep of the tree;
if(cur->left)
{
stk.push(cur->left);
}
else
{// if cur do not have left child;then
if(cur->right)
{
stk.push(cur->right);
}
}
}
else
if(cur->left == pre)//pre is the child of cur; 1 pre is the right child of cur;2 pre is the left child of cur
{// one's left child is vistied then the right child should be visted; => so we try to visit its right child
if(cur->right)
{
stk.push(cur->right);
}
}
else
{// cur->right == pre; then we visit cur; because one's right child is visited then we should visit this node
result.push_back(cur->val);
stk.pop();
}
pre = cur; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
};
http://leetcode.com/2010/10/binary-tree-post-order-traversal.html