My 0ms C++ solution with a boolean flag indicating if this is the second time visiting this node.


  • 0
    W

    New nodes pushed into stack will be marked as false (not visited)
    Children of the node with false flag in the stack will be pushed into stack as new nodes, together with the same node with true flag (visited).
    Nodes with true flag is ready to output its value.

    Although it takes extra space to store the flag, the code is very easy to understand.

    class Solution {
    public:
        vector<int> postorderTraversal(TreeNode* root) {
            vector<int> ret;
            stack<pair<TreeNode*,bool>> s;
    
            s.push(make_pair(root,false));
            
            while(!s.empty()){
                auto p = s.top();
                s.pop();
                if(!p.first)continue;
                if(p.second){
                    ret.push_back(p.first->val);
                }
                else{
                    s.push(make_pair(p.first,true));
                    s.push(make_pair(p.first->right,false));
                    s.push(make_pair(p.first->left,false));
                }
            }
            
            return ret;
        }
    };
    

Log in to reply
 

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