Why Time Limit Exceeded, I can't find the mistake.


  • 0
    L
    class Solution {
    public:
        vector<int> postorderTraversal(TreeNode *root) {
            vector<int> res;
            stack<TreeNode*> poststack;
            TreeNode *lastvisited = NULL;
            TreeNode *cur = root;
            while(!poststack.empty()||cur!=NULL)
                {
                    if(cur)
                    {
                        poststack.push(cur);
                        cur = cur->left;
                    }
                    else
                    {
                        TreeNode *cur = poststack.top();
                        if(!cur->right || lastvisited==cur->right)
                            {cur = cur->right;}
                        else
                        {
                            res.push_back(cur->val);
                            lastvisited = cur;
                            poststack.pop();
                            cur=NULL;
                        }
                    }
                }
            return res;
            
        }
    };

  • 0
    C

    I hava the same proplem,I think the reason is the code process need much time .code is correct and have no mistakes.you should improve algorithm let it process more quickly!


Log in to reply
 

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