Search code examples
javarecursionbinary-search-treecomparable

Adding a Node to a BST recursively using comparable in Java


So I've been trying to insert or add a node to a BST recursively and I'm stumped. I keep getting Exception in thread "main" java.lang.StackOverflowError which I'm assuming is being caused by the recursion, but I don't exactly know where to go from here and would love some direction if anyone could help provide it. :)

public void add(Type obj) {

    TreeNode<Type> newNode = new TreeNode<Type>(obj);

    if (root == null) {
        root = newNode;
    } else {
        addNode(root, newNode);
    }
}


private void addNode(TreeNode<Type> current, TreeNode<Type> newNode) {

    current = root;
    if (current == null) {
        current = newNode;
    } else if (newNode.getValue().compareTo(current.getValue()) < 0) {

        if (current.getLeft() == null) {
            current.setLeft(newNode);

        } else {
            addNode(current.getLeft(), newNode);
        }
    } else if (newNode.getValue().compareTo(current.getValue()) > 0) {

        if (current.getRight() == null) {
            current.setRight(newNode);
        } else {
            addNode(current.getRight(), newNode);
        }
    }
}//end add    

Solution

  • private void addNode(TreeNode<Type> current, TreeNode<Type> newNode) {
    
    current = root;
    if (current == null) {
        current = newNode;
    } else if (newNode.getValue().compareTo(current.getValue()) < 0) {
    
        if (current.getLeft() == null) {
            current.setLeft(newNode);
    
        } else {
            addNode(current.getLeft(), newNode);
        }
    

    Look you are again and again setting the current point equal to root. Which causes StackOverFlow, you should not point to root. You can change it like this: You need to remove this line:

    current = root

    if(root == null){
       root = newNode;
       return;
     }