Search code examples
javarecursiontreestack-overflow

Why is this generating a StackOverflowError


I am a beginner with trees and I was just trying to implement one for the first time and am generating the stackoverfloweror. I know its probably related to a bad recursion call however I dont see anything wrong with the recursion could I get a little help? The error is in this code.

public void insert(Node node, String value)
{
    if((value.compareTo(node.getValue())) < 0)
    {
        if (node.left != null) 
        {
            insert(node.left, value);
        }
        else
            node.left = new Node(value);

    }
    else if((value.compareTo(node.getValue())) > 0)
    {
        if(node.right !=null)
        {
            insert(node.right, value);
        }
        else
            node.right= new Node(value);
    }
}

I call that method here

public static void main(String[] args) throws FileNotFoundException, IOException {
    Tree dataTree = new  Tree(new Node("m"));


    File file = new File("C:\\randomdata.csv");

    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;

    while((line = br.readLine()) != null){
        if(line.toString().contains("zogeti"))
            break;
        else
        {
            dataTree.insert(dataTree.getRootElement(),line);
        }
    }

    br.close();
}

Solution

  • If the file is initially sorted, then this function looks like it will recurse N times for a file with N lines. Java doesn't implement tail recursion, so this is sure to be a real recursion. Rewrite it as a while loop instead of as a recursive function.