[英]Java stackoverflow error on recursive function
when I call this function, why there is a stackoverflow error? 当我调用此函数时,为什么会出现stackoverflow错误? 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 : 看来递归方法应该在
t1
到t2
之间的范围内工作,所以递归调用应该是:
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. 您当前的递归调用永远不会缩小范围(您始终将一个范围从0传递到中间,而将另一个范围从中间传递到
nodeArray
),因此递归永远不会结束。
This is just Debugging 101. 这只是调试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): 用数组[0,1,2,3,4]像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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.