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?
Solution:
/**
* 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;
if(root == NULL) return res;
stack<TreeNode*> st;
st.push(root);
TreeNode* flag = root;
while(!st.empty())
{
TreeNode* top = st.top();
if((top->left == NULL && top->right == NULL) ||
(flag != NULL && (flag == top->left || flag == top->right)))
{
res.push_back(top->val);
st.pop();
flag = top;
}
else
{
if(top->right != NULL) st.push(top->right);
if(top->left != NULL) st.push(top->left);
}
}
return res;
}
};