vector<int> postorderTraversal(TreeNode *root) {
vector<int> res;
if (!root){
return res;
}
stack<TreeNode*> nodes;
TreeNode* cur = root;
TreeNode* pre = NULL;
nodes.push(cur);
if (cur->right){
nodes.push(cur->right);
}
if (cur->left){
nodes.push(cur->left);
}
while (!nodes.empty()){
cur = nodes.top();
if (!cur->left && !cur->right){
nodes.pop();
res.push_back(cur->val);
pre = cur;
continue;
}
if (pre == NULL && cur->right){
nodes.push(cur->right);
}
if (pre == NULL && cur->left){
nodes.push(cur->left);
}
if (pre && (pre == cur->left || pre == cur->right)){
nodes.pop();
pre = cur;
res.push_back(cur->val);
}
else if (pre){
pre = NULL;
}
}
return res;
}