class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> s;
TreeNode* pre;
while(!s.empty() ||root != nullptr){
while(root !=nullptr){
s.push(root);
root = root->left;
}
root = s.top();s.pop();
if(root->right == nullptr || root->right ==pre ){ //如果右子树为空 或者刚刚访问过右子树 代表着是从左边回来的所以我们就可以 输出值并且弹出这个值
res.push_back(root->val);
pre = root;
root = nullptr;
}else{
s.push(root);
root = root->right;
}
}
return res;
}
};