leetcode[145]Binary Tree Postorder Traversal

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) {
        vector<int> res;
        if(root==NULL)return res;
        map<TreeNode *, int> smap;
        smap[root]=0;
        stack<TreeNode *> sta;
        sta.push(root);
        while(!sta.empty())
        {
            TreeNode *p=sta.top();
            if((!p->right&&!p->left)||smap.count(p->right)||smap.count(p->left))
            {
                res.push_back(p->val);
                smap[p]=1;
                sta.pop();
            }
            else
            {
               if(p->right&&!smap.count(p->right))
               {
                sta.push(p->right);
                smap[p->right]=0;
               }
               if(p->left&&!smap.count(p->left))
               {
                sta.push(p->left);
                smap[p->left]=0;
               }
            }
        }
        return res;
    }
/**
void postorder(vector<int> & res,TreeNode *root)
{
    if(root==NULL)return;
    postorder(res,root->left);
    postorder(res,root->right);
    res.push_back(root->val);
}
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> res;
        postorder(res,root);
        return res;
    }
*/
};
原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281219.html