Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [3,2,1]
.
Note: Recursive solution is trivial, could you do it iteratively?
class Solution {
public:
/*algorithm: recursive
*/
void postorder(TreeNode* root,vector<int>&path){
if(!root)return;
postorder(root->left,path);
postorder(root->right,path);
path.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int>path;
postorder(root,path);
return path;
}
};
class Solution {
public:
/*algorithm: iterative
based on rule: postorder sequence is the reverse of preorder sequese
*/
vector<int> postorderTraversal(TreeNode* root) {
vector<int>path;
stack<TreeNode*>preStk;
if(root)preStk.push(root);
while(!preStk.empty()){
TreeNode* t = preStk.top();preStk.pop();
path.push_back(t->val);
if(t->left)preStk.push(t->left);
if(t->right)preStk.push(t->right);
}
//reverse the path to get the post order path
reverse(path.begin(),path.end());
return path;
}
};
class Solution {
public:
/*algorithm: iterative
*/
vector<int> postorderTraversal(TreeNode* root) {
vector<int>path;
stack<TreeNode*>stk;
unordered_set<TreeNode*>accessed;
if(root)stk.push(root);
while(!stk.empty()){
TreeNode* t = stk.top();
if(!accessed.count(t)){
accessed.insert(t);
if(t->right)stk.push(t->right);
if(t->left)stk.push(t->left);
}else{
t = stk.top();stk.pop();
accessed.erase(t);
path.push_back(t->val);
}
}
return path;
}
};