Removendo um Elemento de uma Árvore de Busca Binária
Excluir um elemento de uma árvore de busca binária é um pouco mais complexo do que os passos anteriores, pois precisamos lidar com diferentes casos dependendo do tipo de nó:
- Se o nó não tiver filhos (um nó folha), simplesmente remova-o.
- Se o nó tiver apenas um filho, substitua-o por seu único filho.
- Se o nó tiver dois filhos, substitua-o pelo valor mínimo da subárvore direita ou pelo valor máximo da subárvore esquerda.
public static BSTNode delete(int value, BSTNode current) {
if (current == null)
return current;
if (value < current.value)
current.leftChild = delete(value, current.leftChild);
else if (value > current.value)
current.rightChild = delete(value, current.rightChild);
else if (value == current.value) {
if (current.leftChild != null && current.rightChild != null) {
int min = current.rightChild.value;
BSTNode temp = current.rightChild;
while (temp.leftChild != null) {
min = temp.leftChild.value;
temp = temp.leftChild;
}
current.value = min;
current.rightChild = delete(min, current.rightChild);
} else if (current.leftChild == null)
return current.rightChild;
else if (current.rightChild == null)
return current.leftChild;
}
return current;
}
Para testar este método, exclua alguns nós e imprima a árvore:
public static void main(String[] args) {
BSTNode root = new BSTNode(12);
root = insert(7, root);
root = insert(20, root);
root = insert(5, root);
root = insert(9, root);
root = insert(21, root);
// Delete some nodes
root = delete(12, root);
root = delete(20, root);
root = delete(9, root);
// Print the tree to verify the deletion
System.out.println("Traversal after deletion: ");
inorderTraversal(root);
}
Saída:
Traversal after deletion:
5 7 21