Please Help , Not Able to find a simple error


  • 0
    K

    Please help me finding the bug
    This code is not returning anything(or returning NULL).

    public:
        void maketree(vector<int>& nums,TreeNode *root,int start,int end){
            if(start>end)return;
            int mid=start+(end-start)/2;
            root = new TreeNode(nums[mid]);
            maketree(nums,root->left,start,mid-1);
            maketree(nums,root->right,mid+1,end);
        }
        TreeNode* sortedArrayToBST(vector<int>& nums) {
            TreeNode *root=NULL;
            maketree(nums,root,0,nums.size()-1);
            return root;
        }
    };

  • 0
    J

    I think the error might be that you pass a pointer into maketree(...) by value. The function then copy that pointer, modifies that copy, and end. So your original pointer is never modified.

    You may need to change your function like:
    void maketree(vector<int>& nums,TreeNode *&root,int start,int end)
    and try again.


Log in to reply
 

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