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?
/**
* Definition for binary tree
* 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) {
stack<TreeNode *> tree;
tree.push(root);
TreeNode *q=NULL;
vector<int> a;
if(root==NULL) return a;
while(!tree.empty())
{
TreeNode *p=tree.top();
if((p->left==NULL&&p->right==NULL)||(q!=NULL&&(q==p->left||q==p->right)))
{
a.push_back(p->val);
q=p;
tree.pop();
}
else
{
if(p->right!=NULL)
{
tree.push(p->right);
q=p->right;
}
if(p->left!=NULL)
{
tree.push(p->left);
q=p->left;
}
}
}
return a;
}
};