```
/**
* 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*> stk;
TreeNode *p = root;
vector<int> ans;
while(!stk.empty() || p){
if(p == NULL){
if(stk.top()->right == NULL){
p = stk.top();stk.pop();ans.push_back(p->val);
while(!stk.empty() && p == stk.top()->right){
p = stk.top();stk.pop();ans.push_back(p->val);
}
p = NULL;//important!!
}else{
p = stk.top()->right;
}
} else{
stk.push(p);
p=p->left;
}
}
return ans;
}
};
```