Can someone help please? StackOverflowError on large input


  • 0
    I
    public TreeNode sortedListToBST(ListNode head) 
    {
        if(head == null) return null;
        int size = 0;
        ListNode cur = head;
        while(cur != null)
        {
            size++;
            cur = cur.next;
        }
        return constructBST(head, 1, size);
    }
    
    private TreeNode constructBST(ListNode head, int start, int end)
    {
    	int mid = (start + end) / 2;
    	int index = 1;
    	ListNode cur = head;
    	while(cur != null && index < mid)
    	{
    		index++;
    		cur = cur.next;
    	}
    	TreeNode root = new TreeNode(cur.val);
    	if(cur != head)
    		root.left = constructBST(head, 1, mid-1);
    	if(cur.next != null)
    		root.right = constructBST(cur.next, 1, end - mid);
    	return root;
    }
    

    How can I improve my code? I'm getting the following error:

    Runtime Error Message: Line 46: java.lang.StackOverflowError

    Last executed input: {-999,-998,-997,-996,-995,-994,-993,-992,-991,-990,-989,-988,-987,-986,-985,-984,-983,-982,-981,-980,-979,-9.......

    Thank you!


Log in to reply
 

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