Search code examples
javabinary-treeis-empty

Method isEmpty for binary tree issue


I am trying to write myself the isEmpty method for a binary tree but I am having a problem. So this is the method that I am using.

public boolean isEmpty(){
if(root == null) return true;
else return false;
}

When I add only one element, and then remove this element, and call isEmpty, I do not get true, but false.

Is there somethng wrong with my implementation?


So this is the remove method:

  /**
    * Internal method to remove from a subtree.
    * @param x the item to remove.
    * @param t the node that roots the tree.
    * @return the new root.
    * @throws ItemNotFoundException if x is not found.
    */
    protected BinaryNode<AnyType> remove( AnyType x, BinaryNode<AnyType> t )
    {
    if( t == null )
    throw new ItemNotFoundException( x.toString( ) );
    if( x.compareTo( t.element ) < 0 )
    t.left = remove( x, t.left );
    else if( x.compareTo( t.element ) > 0 )
    t.right = remove( x, t.right );
    else if( t.left != null && t.right != null ) // Two children
    {
    t.element = findMin( t.right ).element;
    t.right = removeMin( t.right );
    }
    else
    t = ( t.left != null ) ? t.left : t.right;
    return t;
    }

and this is the removeMin method that the remove method uses:

        /**
         * Internal method to remove minimum item from a subtree.
         * @param t the node that roots the tree.
         * @return the new root.
         * @throws ItemNotFoundException if t is empty.
         */
         protected BinaryNode<AnyType> removeMin( BinaryNode<AnyType> t )
         {
         if( t == null )
        throw new ItemNotFoundException( );
        else if( t.left != null )
        {
        t.left = removeMin( t.left );
        return t;
        }
        else
        return t.right;
        }

Solution

  • Check your remove element code. Usually than code find out parent of remove node and set to null corresponding reference. And for last element it have to set to null root variable.