Where my code called "Memory limited exceed"


  • 2
    H
       Memory Limited exceed
    
    class Solution {
        public:
        	TreeNode *sortedArrayToBST(vector<int> &num) {
        		int len = num.size();
        		if (len == 0)
        		{
        			return NULL;
        		}
        		return sortArr(num,0,len-1);
        	}
        	TreeNode *sortArr(vector<int> num, int begin,int end)
        	{
        		TreeNode *p = NULL;
        		if ( begin > end)
        		{
        			return p;
        		}
        		int mid = (begin+end) / 2;
        		p = new TreeNode(num[mid]);
        		p->left = sortArr(num,begin,mid-1);
        		p->right = sortArr(num,mid+1,end);
        		return p;
        	}
        };

  • 5
    S
        TreeNode *sortArr(vector<int> &num, int begin,int end)  // passing reference of num instead of value, or the recursion will waste lots of memory.
        {
            TreeNode *p = NULL;
            if ( begin > end)
            {
                return p;
            }
            int mid = (begin+end) / 2;
            p = new TreeNode(num[mid]);
            p->left = sortArr(num,begin,mid-1);
            p->right = sortArr(num,mid+1,end);
            return p;
        }

  • 0
    M

    Try passing num by reference in sortArr function.


Log in to reply
 

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