Why am I getting runtime error?


  • 0
    B

    Here's my solution:

    TreeNode *sortedArrayToBST(vector<int> &num) {
        if(num.size()==0)
        {
            return NULL;
        }
        
        return A(num, 0, num.size()-1);
    }
    
    TreeNode *A(vector<int> &num, int start, int end) {
        int rootInd = start + (end-start+1)/2;
        
        TreeNode root (num[rootInd]);
        
        if(rootInd > start)
        {
            root.left = A(num, start, rootInd-1);
        }
        
        if(rootInd < end)
        {
            root.right = A(num, rootInd+1, end);
        }
        
        return &root;
    }
    

    When I submit on OJ, I always get "Runtime error, Last executed input: [0] ". However when I run it in VS with the test data "[0]", it worked fine and gives the expected result. Can anyone give me any advice?


  • 1
    S

    TreeNode root (num[rootInd]); should change to TreeNode *root = new TreeNode (num[rootInd]);.

    ------UPDATE -----

    TreeNode root (num[rootInd]); is using stack memory, the other is using heap memory. The difference between them is variable in stack memory will be popped off by the time of exiting the function.


  • 0
    B

    Thank you. It worked. And can you help me understand what's the problem with "TreeNode root (num[rootInd]);" ? It looks fine to me...


  • 0
    S

    I updated my answer.


Log in to reply
 

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