Search code examples
javadata-structuresbinary-search-tree

What's wrong with my insert() method in my Binary Search Tree implementation?


I tried to create a recursive method to insert an element into my binary search tree; however, I can't seem to find the error in my code (I suspect it has something to do with references).

public class BST<E extends Comparable<E>> {

    private class BSTNode implements Comparable<BSTNode> {

        public E data;
        public BSTNode left;
        public BSTNode right;

        public BSTNode(E data) {
            this.data = data;
        }

        @Override
        public int compareTo(BSTNode o) {
            return this.data.compareTo(o.data);
        }
    }

    public BSTNode root;

    public void insert(E data) {
        insertRec(root, new BSTNode(data));
    }

    private void insertRec(BSTNode current, BSTNode newNode) {
        if (current == null) {
            current = newNode;
            return;
        }
        if (current.compareTo(newNode) > 0) {
            insertRec(current.right, newNode);
        }
        else if (current.compareTo(newNode) < 0) {
            insertRec(current.left, newNode);
        }
    }


Solution

  • This makes no sense:

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

    current.right and current.right can be null, so you never actually add something to a Node.

    To set something you would need to do i.e. current.right = newNode

    This should work:

    public class BST<E extends Comparable<E>> {
    
        private class BSTNode implements Comparable<BSTNode> {
    
            public E data;
            public BSTNode left;
            public BSTNode right;
    
            public BSTNode(E data) {
                this.data = data;
            }
    
            @Override
            public int compareTo(BSTNode o) {
                return this.data.compareTo(o.data);
            }
        }
    
        public BSTNode root;
    
        public void insert(E data) {
            root = insertRec(root, new BSTNode(data));
        }
    
        private BSTNode insertRec(BSTNode current, BSTNode newNode) {
            if (current == null){
                return newNode;
            }
    
            if (current.compareTo(newNode) > 0) {
               current.right = insertRec(current.right, newNode);
            } else {
                current.left = insertRec(current.left, newNode);
            }
    
            return current;
        }
    }