Why I get a runtime error?

• ``````public class Solution {
public TreeNode sortedArrayToBST(int[] num) {
if(num == null){
return null;
}
if(num.length == 1){
return new TreeNode(num[0]);
}
int mid = (num.length-1) /2;
TreeNode root = new TreeNode(num[mid]);
root.left = breakArray(0, mid-1, num, root);
root.right = breakArray(mid+1,num.length-1,num,root);
return root;
}
public TreeNode breakArray(int start, int end, int[] num, TreeNode root){
if(start == end){
return new TreeNode(num[start]);
}
if(start > end){
return null;
}
int mid = (end-start)/2;
TreeNode n_root = new TreeNode(num[mid]);
root.left = breakArray(start, mid-1, num, n_root);
root.right = breakArray(mid+1,end,num,n_root);
return n_root;
}
}
``````

I tried several tests in IDEONE, an online compiler and it runs smoothly. I don't know why it just went wrong here. Thank you!

• Not sure if this is causing the runtime error, but you are calculating 'mid' incorrectly. For example if start = 5, and end = 10, you will compute mid = 2 which is incorrect. Also, as a side comment, you have some redundant code that can be collapsed into just one recursive function.

• Thank you very much. Would you like to explain "redundant code" a little more?

• Well, both your functions have overlapping code (ie find mid, assign left/right, etc). Instead you could have just one recursive function that does all that. And your function "sortedArrayToBST" just becomes a wrapper that calls the recursive function with appropriate arguments (eg, int [], start = 0, end=length-1). Try it out, if you are stuck and would like to see my solution, let me know.

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