简体   繁体   中英

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;
    }
}

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM