Iterative easy solution without Morris


  • 0
    S
    /**
     * 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;
            stack<pair<TreeNode *, bool> > s;
            if(root)
                s.push(make_pair(root, false));
            while(!s.empty())
            {
                pair<TreeNode *, bool> p = s.top();
                if(p.second)
                {
                    res.push_back(p.first->val);
                    s.pop();
                    continue;
                }
                s.top().second = true;
                if(p.first->right)
                    s.push(make_pair(p.first->right, false));
                if(p.first->left)
                    s.push(make_pair(p.first->left, false));
            }
            return res;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.