What is the overflow error of my code?


  • 0
    S

    Hi guys, I am looking for some help on this error of my code. The compiler says

    Line 23: java.lang.StackOverflowError.

    But I can't find the error. Could anyone give me some hints? Being a rookie on programming, might make stupid mistakes.

    public class Solution {
    
        public TreeNode sortedArrayToBST(int[] num) {
            if(num == null || num.length == 0) return null;
            
            return toBST(num, 0, num.length);
        }
        
        public TreeNode toBST(int[] arr, int i, int j){
            
            if(i>=j) return null;
            
            int mid = (i+j)/2;
            TreeNode node = new TreeNode(arr[mid]);
            node.left = toBST(arr, 0, mid);
            node.right = toBST(arr, mid+1, arr.length);
            return node;
            
        }
    }

  • 0
    Z

    return toBST(num, 0, num.length); should be return toBST(num, 0, num.length - 1);

    &&

    if(i>=j) return null; should be if(i > j) return null;


  • 0
    Z
    This post is deleted!

  • 0
    S

    Thanks for pointing that out. I think I have found the issue. Indeed the issues include what you mentioned below. I can make a list of them.

    1. return toBST(num, 0, num.length) should be return toBST(num, 0, num.length -1)
    2. if(i>=j) return null; should be if(i>j).
      3, node.left = toBST(arr, 0, mid); should be node.left = toBST(arr, 0, mid-1);
    3. node.right = toBST(arr, mid+1, arr.length); should be node.right = toBST(arr, mid+1, j);

    Gosh, looks like nothing was right. But thanks to all for taking the look at my code and pointing out my errors.


  • 0
    S

    Thanks for pointing that out. Looks like I made more mistakes.


Log in to reply
 

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