类似前序遍历,不过入栈时是先left再right,得到根右左,再对结果反转得到左右根
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> res;
if(root == nullptr)
return res;
stack<TreeNode*> st;
st.push(root);
while(!st.empty())
{
TreeNode* cur = st.top();
st.pop();
if(cur!=nullptr){
res.push_back(cur->val);
st.push(cur->left);
st.push(cur->right);
}
}
reverse(res.begin(),res.end());
return res;
}
};