145. Binary Tree Postorder Traversal (Hard)
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?
postorder: left-right-middle
Solution 1: recursive
/**
* 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 {
void postOrder(TreeNode *root, vector<int> &res) {
if (root) {
postOrder(root->left, res);
postOrder(root->right, res);
res.push_back(root->val);
}
}
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
postOrder(root, res);
return res;
}
};
Solution 2: iterative
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if (!root) return res;
stack<TreeNode*> s;
s.push(root);
TreeNode *head = root;
while (!s.empty()) {
TreeNode* top = s.top();
// push node if it has no children, or its children has been visited
if ((!top->left && !top->right) || top->left == head || top->right == head) {
res.push_back(top->val);
s.pop();
head = top;
} else {
if (top->right) s.push(top->right);
if (top->left) s.push(top->left); // last in fist out
// test left node first
}
}
return res;
}