解法一 recursion
class Solution {
public:
vector<int> res;
vector<int> postorderTraversal(TreeNode * root) {
res.clear();
helper(root);
return res;
}
void helper(TreeNode* root){
if(!root) return;
helper(root->left);
helper(root->right);
res.push_back(root->val);
}
};
解法二 non-recursion
class Solution {
public:
vector<int> postorderTraversal(TreeNode * root) {
stack<TreeNode*> st;
vector<int> res;
TreeNode* cur = root;
TreeNode* last;
while(cur || !st.empty()){
while(cur){
st.push(cur);
cur = cur->left;
}
cur = st.top();
if(!cur->right || last==cur->right){
res.push_back(cur->val);
st.pop();
last= cur;
cur = NULL;
}else cur = cur->right;
}
return res;
}
};