/** * Internal method to insert into a subtree. * * @param x the item to insert. * @param t the node that roots the tree. * @return the new root. * @throws DuplicateItemException if x is already present. */ protected BinaryNode<AnyType> insert(AnyType x, BinaryNode<AnyType> t) { if (t == null) t = new BinaryNode<AnyType>(x); else if (x.compareTo(t.element) < 0) t.left = insert(x, t.left); else if (x.compareTo(t.element) > 0) t.right = insert(x, t.right); else throw new DuplicateItemException(x.toString()); // Duplicate return t; }
/** * 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; }