javabinarybinary-treebinary-search-treetreap

How to insert a node onto a Treap with three arguments


I am having issues inserting a Treapnode into a treap. It takes in 3 arguments. add(E key, P priority, treapnode x). I have tried many things and keep getting a null pointer exception.

I have tried checking for null cases in both the left and the right tree.

private TreapNode add (E key, P priority, TreapNode x)
        throws ElementFoundException {

    // For You To Complete
    int compare = key.compareTo(x.element());
    if (x == null){
        return new TreapNode(key, priority);
    }

    //root is larger than the key

    else if (compare == 0) {
        throw new ElementFoundException("Element was found, and tree was not changed.");
    } else if (compare < 0) {
        if (x.left() == null) {
         //TreapNode y = new TreapNode(key, priority);
            TreapNode y = x.left;
            x.left = y.right;
            y.right = x;
            return y;
        } else {
            x.left = add(key, priority, x.left());
        }


    }
    //root is smaller than the key
    else if (compare > 0) {
        if (x.right() == null) {
            //TreapNode y = new TreapNode(key, priority);
            TreapNode z = x.right;
            x.right = z.left;
            z.left = x;
            return z;
        }

    }
    return x;
}

Solution

  • this is you are doing wrong with x.right(). same is the case with x.left()

    if (x.right() == null) {
            //TreapNode y = new TreapNode(key, priority);
            TreapNode z = x.right; // z = null
            x.right = z.left;  // z.left will throw NPE
    

    should be

    if (x.right() == null) {
       x.right() = new TreapNode(key, priority);
       return x; // return parent node 
    }
    

    also, I think this is also a wrong comparison, int can't be null but Integer class can be

    int compare = key.compareTo(x.element());  //comoareTo return an int 
    if (x == null){  // does not make sense to compare and int type to Object type
      ....
    }
    

    for in-depth understanding read this page https://www.geeksforgeeks.org/binary-search-tree-set-1-search-and-insertion/