Eric
Eric

Reputation: 11

Java stackoverflow error on recursive function

when I call this function, why there is a stackoverflow error? I have checked my terminal conditions but can not figure out where the problem is.

public static TreeNode buildTree(int t1, int t2, ListNode[] nodeArray) {     
    if(t1 == t2){
        TreeNode temp = new TreeNode(nodeArray[t1].val);
        temp.left = null;
        temp.right = null;
        return temp;
    }
    else if(t1 > t2){
        return null;
    }

    else{   
        TreeNode root = new TreeNode(nodeArray[(t1+t2)/2].val);
        root.left = buildTree(0,(t1+t2)/2-1,nodeArray);
        root.right = buildTree((t1+t2)/2+1,nodeArray.length-1,nodeArray);
        return root;
    }
}

Upvotes: 1

Views: 108

Answers (3)

kumade
kumade

Reputation: 541

Simple example of calling Your method with an array [0, 1, 2, 3, 4] like buildTree(0, 4, array):

1    root = 2;
2    buildTree(0, 1);
3        root = 0;
4        buildTree(0, -1);
5            null;
6        buildTree(1, 4);
7            root = 2;
8            buildTree(0, 1); // endless recursion. see 2nd line call

Upvotes: 0

Eran
Eran

Reputation: 393771

It looks like the recursive method should be working on a range between t1 and t2, so the recursive calls should be :

root.left = buildTree(t1,(t1+t2)/2-1,nodeArray);
root.right = buildTree((t1+t2)/2+1,t2,nodeArray);

Your current recursive calls never narrow the range (you always pass one range from 0 to the middle and another range from the middle to the end of nodeArray), so the recursion never ends.

Upvotes: 6

paxdiablo
paxdiablo

Reputation: 881153

This is just Debugging 101.

Place the following line as the first in the method:

System.out.println("Entry, t1 = " + t1 + ", t2 = " + t2);

From that, you will be able to work out the flow.

Upvotes: 0

Related Questions