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)
{
stack<TreeNode*> S;
TreeNode* x=root;
vector<int> post_tra;
if(!root) return post_tra;
else S.push(root);
while(!S.empty())
{
if(x!=S.top()->right && x!=S.top()->left)
find(S);
x = S.top();
S.pop();
post_tra.push_back(x->val);
}
return post_tra;
}
void find(stack<TreeNode*>& S)
{
while(TreeNode* x = S.top())
{
if(x->left)
{
if(x->right) S.push(x->right);
S.push(x->left);
}
else
S.push(x->right);
}
S.pop();
}
};