/**
* 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)
{
vector<int>vect;
stack<TreeNode*>stk;
TreeNode *cur;
TreeNode *pre=NULL;
if(root==NULL)
{
return vect;
}
else
{
stk.push(root);
while(!stk.empty())
{
cur=stk.top();
if((cur->left==NULL&&cur->right==NULL)||((pre!=NULL)&&(pre==cur->left||pre==cur->right)))
{
//(pre==cur->left||pre==cur->right)说明cur的孩子已经压进来,不然还要压!因为孩子一定比根先出栈
pre=cur;
}
else
{
if(cur->right!=NULL)
{
stk.push(cur->right);
}
if(cur->left!=NULL)
{
stk.push(cur->left);
}
}
}
}
}
};
* 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)
{
vector<int>vect;
stack<TreeNode*>stk;
TreeNode *cur;
TreeNode *pre=NULL;
if(root==NULL)
{
return vect;
}
else
{
stk.push(root);
while(!stk.empty())
{
cur=stk.top();
if((cur->left==NULL&&cur->right==NULL)||((pre!=NULL)&&(pre==cur->left||pre==cur->right)))
{
//(pre==cur->left||pre==cur->right)说明cur的孩子已经压进来,不然还要压!因为孩子一定比根先出栈
vect.push_back(cur->val);
stk.pop();pre=cur;
}
else
{
if(cur->right!=NULL)
{
stk.push(cur->right);
}
if(cur->left!=NULL)
{
stk.push(cur->left);
}
}
}
}
}
};