Why this cause an RE?


  • 0
    A

    The comment part in function toBST !!! Why use static memory will return Runtime Error, and use danymic memory will return AC???

    class Solution {
    public:
    TreeNode * sortedListToBST(ListNode * head)
    {
        int len = getListLen(head);
        return toBST(head, len);
    }
    
    private:
    TreeNode * toBST(ListNode * head, int n)
    {
        if (head == NULL || n == 0) return NULL;
        int m = (n+1) / 2;
        ListNode * mid = head;
        for (int i = 1; i < m; ++i) mid = mid->next;
        // TreeNode root(mid->val);
        // root.left = toBST(head, m-1);
        // root.right = toBST(mid->next, n-m);
        // return &root;
        TreeNode * root new TreeNode(mid->val);
        root->left = toBST(head, m-1);
        root->right = toBST(mid->next, n-m);
        return root;
    }
    int getListLen(ListNode * head)
    {
        int len = 0;
        while (head) {
            len += 1;
            head = head->next;
        }
        return len;
    }
    };

  • 0
    A

    You are returning pointer that points to stack object. The object is destroyed upon exiting the function.


  • 0
    A

    Oh, I see... So, the object in heap won't be destroy when exiting the function?


Log in to reply
 

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