remove(root.getRight(), value);
}
// value found - check if has 2 branches
else if (root.getRight() != null && root.getLeft() != null)
{
Node min = minValue(root.getRight());
removeMin(root);
min.setLeft(root.getLeft());
min.setRight(root.getRight());
Node ancesstor = findPredecessor(root);
if (ancesstor == null)
{
this.root = min;
}
else if (root == ancesstor.getLeft())
{
ancesstor.setLeft(min);
}
else
{
ancesstor.setRight(min);
}
}
else
// if has 1 branch or less
{
// find the father of the node to delete
Node ancesstor = findPredecessor(root);
// if the value to delete is in the root
if (ancesstor == null)
{
if (root.getRight() != null || root.getLeft() != null)
{
this.setRoot(root.getLeft() == null ? root.getRight()
: root.getLeft());
}
else
{
throw new ItemNotFoundException(
"Can not remove the only node in the tree. "
+ "A binary search tree must have at least 1 value.");
}
} // if not root check if the father's left is not null
else if (ancesstor.getLeft() != null)
{ // if not null, check if to be deleted
if (ancesstor.getLeft().getData().compareTo(value) == 0)
{ // if to be deleted replace the target by the son
ancesstor.setLeft(root.getRight() == null ? root
.getLeft() : root.getRight());
}
else
{
ancesstor.setRight(root.getRight() == null ? root
.getLeft() : root.getRight());
}
}
else
{
if (ancesstor.getRight().getData().compareTo(value) == 0)
{ // if to be deleted replace the target by the son
ancesstor.setRight(root.getRight() == null ? root
.getLeft() : root.getRight());
}
else
{
ancesstor.setLeft(root.getRight() == null ? root
.getLeft() : root.getRight());
}
}
}
}