145. Binary Tree Postorder Traversal
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?
Solutioin:
Super Easy.
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector <int> ans;
if (root == NULL)
return ans;
stack <TreeNode*> s; s.push(root);
while (!s.empty()) {
TreeNode* x = s.top();
bool pop = true;
if (x -> right) {
s.push(x -> right);
x -> right = NULL;
pop = false;
}
if (x -> left) {
s.push(x -> left);
x -> left = NULL;
pop = false;
}
if (pop) {
ans.push_back(x -> val);
s.pop();
}
}
return ans;
}
};