Home > database >  Implementing Add Method for BST
Implementing Add Method for BST

Time:11-20

I am trying to implement an insertion method in a BST but have encountered some problems. Given the surrounding code:

public class BinarySearchTree<E> {
  private BinaryNode<E> root;  
  private int size;          
  private Comparator<E> comparator;

    /**
     * Constructs an empty binary search tree, sorted according to the specified comparator.
     */
    public BinarySearchTree(Comparator<E> comparator) {
        root = null;
        size = 0;
        this.comparator = comparator;
    }

    private static class BinaryNode<E> {
        private E element;
        private BinaryNode<E> left;
        private BinaryNode<E> right;

        private BinaryNode(E element) {
            this.element = element;
            left = right = null;
        }   
    }

     //Other methods
}

what is wrong with my implementation:


    /**
     * Inserts the specified element in the tree if no duplicate exists.
     * @param x element to be inserted
     * @return true if the the element was inserted
     */
    public boolean add(E x) {
        return add(root, x);
    }

    private boolean add(BinaryNode<E> n, E x) {
        if(n == null) {
            n = new BinaryNode<E> (x);
            size  ;
            return true;
        }
        int compResult = comparator.compare(x, n.element);
        
        if(compResult<0){
            return add(n.left, x);
        } else if(compResult>0) {
            return add(n.right, x);
        }else {
            return false;
        }
    }

When testing inserting only one element I get null as the return value of the root but I can't really see what's going wrong. Thanks for the help!

CodePudding user response:

When you assign

    n = new BinaryNode<E> (x)

in add() you are assigning to a local variable. That doesn't add the new node to the tree; there are no references from the existing tree to the new node that way.

There are numerous ways to fix it, but this is likely the reason why you never see root change away from null; you never assign to it anywhere.

Pointers would be nice here, they make it easier to pass a variable by reference, but in Java I think you would need to pass along the location where you need to put the new node some other way. I haven't used the language in 20 years, so I am not too sure, though.

  • Related