Runtime error with test case[0,1,2,3,4,5,6],but debug at Eclipse can get right BST Tree, why?


  • 0
    F

    My code as below, Runtime error with test case[0,1,2,3,4,5,6],but debug at Eclipse can get right BST Tree(inorder traverse the tree get result: 0 1 2 3 4 5 6), why?It's sor weird.

    class Solution {

    public:

    ListNode* getMid(ListNode* start, ListNode* end) {
        ListNode *low, *fast;
        low = start;
        fast = start->next;
        while(fast && fast->next) {
            low = low->next;
            fast = fast->next->next;
        }
        return low;
    }
    
    TreeNode* insertBST(ListNode* start, ListNode* end) {
        TreeNode* p = NULL;
        if(start == end) {//no node in list
            return NULL;
        }
        if(start->next == end) {//one node in list
            p = new TreeNode(start->val);
        } else if(start->next->next==end) {//two node in list
            p = new TreeNode(start->val);
            p->right = new TreeNode(start->next->val);
        } else {
            ListNode *mid = getMid(start, end);
            p = new TreeNode(mid->val);
            p->left = insertBST(start, mid);
            p->right = insertBST(mid->next, end);
        }
        
        return p;
    }
    TreeNode* sortedListToBST(ListNode* head) {
        return insertBST(head, NULL);
    }
    

    };


Log in to reply
 

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