在这里插入代码片
class Solution {
public:
vector postorderTraversal(TreeNode* root) {
vector res;
if(!root){
return res;
}
stack stk;
TreeNode* node=nullptr;
while(root!=nullptr || !stk.empty()){
while(root!=nullptr){
stk.emplace(root);
root=root->left;
}
root=stk.top();
stk.pop();
if(root->right==nullptr || root->right==node){//当该节点为叶子节点或者被访问过时,直接推入数组;
res.emplace_back(root->val);
node=root;
root=nullptr;
}
else{
//不是叶子节点且没有被访问过值,则推入栈中
stk.emplace(root);
root=root->right;
}
}
return res;
}
};



