Solution with one stack and one lastvisited Node, what is wrong with it? please help


  • 0
    H
    vector<int> postorderTraversal(TreeNode *root) 
    {
        vector <int> out={};
        if(!root)
        {
            return( out);
        }
        stack <TreeNode*> S;
    
        TreeNode * c=root;
        TreeNode * lastvisited=root;
        while(c)
        {
            S.push(c);
            c=c->left;
        }
        
        while(!S.empty())
        {
            
            c=S.top();
            
            if( c->right==lastvisited |  c->right==NULL &  c->left==NULL | c->left==lastvisited & c->right==NULL)
            {
                out.insert( out.end(), c->val );
                lastvisited=c;
                S.pop();
    
            }
            c=c->right;
            while(c)
            {
                S.push(c);
                c=c->left;
                
            }
            
        }
    }

Log in to reply
 

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