My code shows memory limit exceeded

  • 2
       TreeNode *sortedArrayToBST(vector<int> &nums) {
          int l = 0;
          int r  = nums.size()-1;
          if(r == -1)return NULL;// if there is no element
          TreeNode *root = cr(nums,l,r);//create tree
          return root;
       TreeNode *cr(vector<int>nums,int l,int r){//function will return the root of tree
          if(l > r)return NULL;
          int mid = (l+r)/2; // take the mid element as root;
          TreeNode *tmp = new TreeNode(nums[mid]);//create node with mid value
          tmp->left = cr(nums,l,mid-1); // recursively construct left sub-tree
          tmp->right = cr(nums,mid+1,r);// and right sub tree
          return tmp;

  • 0

    Please format your code correctly. Update your post to detail your algorithm in some words, and make key comments in your code.

  • 11

    I get it. Your problem is not relevant to the algorithm, but the implementation.

    Pay attention to this statement TreeNode *cr(vector<int>nums,int l,int r). You pass nums by value, not by reference, so every time you call the function cr, it will copy the big vector one more time. So in your recursion process, this behavior will cost large memory.

  • 0

    thank you sir...

Log in to reply

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