Solution:
The post-order is the reverse of the root->right->left order. The root->right->left order is similar to pre-order traversal. Thus we first do a pseudo-pre-order traversal, by collecting root first, then right node, then left node. As we collect all nodes we reverse the collection.
Code:
/**
* Definition for a binary tree node.
* 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) {
stack<TreeNode*> stk1;
stack<TreeNode*> stk2;
if(root) stk1.push(root);
TreeNode*cur;
while(!stk1.empty()){
cur = stk1.top();
stk1.pop();
stk2.push(cur);
if(cur->left) stk1.push(cur->left);
if(cur->right) stk1.push(cur->right);
}
vector<int> res;
while(!stk2.empty()){
res.push_back(stk2.top()->val);
stk2.pop();
}
return res;
}
};