Why Memory Limit Exceeded


  • 0
    Y
        class Solution {
        public:
            TreeNode *build(vector<int> &preorder, vector<int> &inorder, int bp, int ep, int bi, int ei){
            // bp(ep) : begin(end) index of preorder;
            // bi(ei) : begin(end) index of inorder;
            //the first element in preorder is the root, find root in inorder,
            //then the left part of root in inorder is the left child
           // and right part is the right child, recursively build left subtree and right subtree.
                if(ep - bp < 0)
                    return NULL;
                if(ep == bp)
                    return new TreeNode(inorder[ep]);
                TreeNode *result = new TreeNode(preorder[bp]);
                int l = 0;
                /*find root in the inorder vector*/
                for(int i=bi; i<= ei; i++){
                    if(inorder[i] == preorder[bp])
                        break;
                    l++;
                }
                TreeNode *left = build(preorder, inorder, bp+1, bp+l, bi, bi+l-1); 
                TreeNode *right = build(preorder, inorder, bp+l+1, ep, bi+l, ei);
                result->left = left;
                result->right = right;
                return result;
            }
            TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
                int n = preorder.size();
                if(n == 0)
                    return NULL;
                return build(preorder, inorder, 0, n-1, 0, n-1);
            }
        };
    

    And I get Memory Limite Exceeded, Could you help me to figure out the issue?


Log in to reply
 

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