145. Binary Tree Postorder Traversal
problem description
Input: [1,null,2,3]
1
\
2
/
3
Output: [3,2,1]
Follow up: Recursive solution is trivial, could you do it iteratively?algorithm thought
code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()){
TreeNode* tmp=st.top();
st.pop();
while(tmp){
res.push_back(tmp->val);
st.push(tmp->left);
tmp=tmp->right;
}
}
reverse(res.begin(),res.end());
return res;
}
};algorithm analysis
Last updated