迭代:
typedef pair<int, TreeNode*> P;
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> out;
stack<P> stk;
stk.push(P(0, root));
while(stk.size() > 0) {
P temp = stk.top();
stk.pop();
if(!temp.second) continue;
if(!temp.first) {
stk.push(P(1, temp.second));
stk.push(P(0, temp.second->right));
stk.push(P(0, temp.second->left));
} else {
out.push_back(temp.second->val);
}
}
return out;
}
};
递归:
class Solution {
void postorder(vector<int>& ans, TreeNode* tree){
if(!tree) return;
postorder(ans, tree->left);
postorder(ans, tree->right);
ans.push_back(tree->val);
}
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> out;
postorder(out, root);
return out;
}
};
|