Given a binary tree, return the postorder traversal of its nodes' values.
Example:
Input:[1,null,2,3]
1 \ 2 / 3 Output:[3,2,1]
Follow up: Recursive solution is trivial, could you do it iteratively?
/**
* 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;
TreeNode *p = root;
stack<TreeNode *> sta;
TreeNode *last = root;
sta.push(p);
while (!sta.empty())
{
p = sta.top();
if( (p->left == NULL && p->right == NULL) || (p->right == NULL && last == p->left) || (last == p->right) )
{
res.push_back(p->val);
last = p;
sta.pop();
}
else
{
if(p->right)
sta.push(p->right);
if(p->left)
sta.push(p->left);
}
}
return res;
}
};