Why always "Memory Limit Exceeded"


  • 1
    A

    Below is my code, not sure why always met the "Memory Limit Exceeded" error?

    /**
     * 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> preorderTraversal(TreeNode *root) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            stack<TreeNode*> tempStack;
            vector<int> vOutput;
            if(root)
            {
                tempStack.push(root);
                while(!tempStack.empty())
                {
                    TreeNode* pNode = tempStack.top();
                    assert(pNode);
                    vOutput.push_back(pNode->val);
                    tempStack.pop();
                    if(root->right)
                        tempStack.push(root->right);
                    if(root->left)
                        tempStack.push(root->left);
                }
            }
            
            return vOutput;
        }
    };

  • 11
    E

    There is a bug in your code. You always use root to push to your stack!
    Use the below code can get a AC.

            if(pNode->right)
                tempStack.push(pNode->right);
            if(pNode->left)
                tempStack.push(pNode->left);

  • 0
    A

    OMG...Thank you very much!


  • 0
    C
    This post is deleted!

Log in to reply
 

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