```
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> s;
vector<int> res;
if(!root) return res;
TreeNode* cur; //current node
TreeNode* pre=NULL; //previous node
s.push(root);
while(!s.empty()) {
cur=s.top();
if((cur->left==NULL&&cur->right==NULL)||
(pre!=NULL&&(pre==cur->left||pre==cur->right))) {
//if current node is leaf node or its child nodes have been visited
res.push_back(cur->val);
s.pop();
pre=cur;
}
else {
if(cur->right!=NULL) s.push(cur->right);
if(cur->left!=NULL) s.push(cur->left);
}
}
return res;
}
};
```