Example #1
0
    public T pop()
    {
        if (root == null)
        {
            return(default(T));
        }

        Queue <HeapNode <T> > q    = new Queue <HeapNode <T> >();
        HeapNode <T>          curr = root;
        HeapNode <T>          prev = null;

        while (curr != null)
        {
            HeapNode <T> l = curr.getLeft();
            q.Enqueue(l);

            HeapNode <T> r = curr.getRight();
            q.Enqueue(r);

            prev = curr;
            curr = q.Dequeue();
        }

        //case where root is the only one
        //handle it here to avoid null pointers below
        if (prev.Equals(root))
        {
            root = null;
            return(prev.getNode());
        }

        //set last element in tree to root node
        //set roots left and right to new root left and right
        prev.setLeft(root.getLeft());
        prev.setRight(root.getRight());

        //set new root parents to this
        if (prev.getLeft() != null)
        {
            prev.getLeft().setParent(prev);
        }
        if (prev.getRight() != null)
        {
            prev.getRight().setParent(prev);
        }

        //set prev's old parent's left or right branch to null
        if (prev.getParent().getLeft().Equals(prev))
        {
            prev.getParent().setLeft(null);
        }
        else if (prev.getParent().getRight().Equals(prev))
        {
            prev.getParent().setRight(null);
        }

        //set prev parent to null since it will be the root
        prev.setParent(null);

        HeapNode <T> popVal = root;

        root = prev;

        //place prev in its correct place
        //root.sort();
        root = root.sortChild();

        //completely disconnect popped value from tree
        popVal.setParent(null);
        popVal.setLeft(null);
        popVal.setRight(null);

        return(popVal.getNode());
    }