currentNode.setLeftNode(inserer_rec(currentNode.getLeftNode(), value));
} else if (value > currentNode.getData()) {
currentNode.setRightNode(inserer_rec(currentNode.getRightNode(), value));
- } else {
- /* equality */
- return currentNode;
- }
+ } /* skip the equality case */
return currentNode;
}
} else if (currentNode.getLeftNode() == null) {
return currentNode.getRightNode();
} else {
+ /*
+ * First, we need to find the node that will replace the deleted node.
+ * We’ll use the smallest node of the node to be deleted’s right sub-tree.
+ * Then, we assign the smallest value to the node to delete and after that,
+ * we’ll delete it from the right subtree.
+ */
int smallestValue = findSmallestData(currentNode.getRightNode());
currentNode.setData(smallestValue);
currentNode.setRightNode(supprimer_rec(currentNode.getRightNode(), smallestValue));
}
public boolean hasData(int value) {
- return hasDataRec(rootNote, value);
+ return hasDataRec(rootNode, value);
}
private int findSmallestData(IntNode node) {
return node.getLeftNode() == null ? node.getData() : findSmallestData(node.getLeftNode());
}
- public afficher_rec(IntNode currentNode) {
- if (currentNode.getLeftNode() != null) {
+ private void afficher_rec(IntNode currentNode) {
+ if (currentNode != null) {
afficher_rec(currentNode.getLeftNode());
- } else if (currentNode.getRightNode() != null) {
+ System.out.print(currentNode.getData() + " ");
afficher_rec(currentNode.getRightNode());
}
- System.out.println("Valeur dans le noeud : ");
+ }
+
+ public void afficher() {
+ afficher_rec(rootNode);
+ System.out.println();
+ }
+
+ private void afficher_arbre_rec(IntNode currentNode, int column) {
+ int i;
+
+ if (currentNode != null) {
+ afficher_arbre_rec(currentNode.getRightNode(), column + 1);
+ for (i = 0; i < column; i++) {
+ System.out.print(" ");
+ }
+ System.out.println(currentNode.getData());
+ afficher_arbre_rec(currentNode.getLeftNode(), column + 1);
+ }
+ }
+
+ public void afficher_arbre() {
+ afficher_arbre_rec(rootNode, 1);
}
public static void main(String[] args) {
ArbreBinaire Btree = new ArbreBinaire();
- Btree.inserer(5);
Btree.inserer(2);
- Btree.inserer(7);
+ Btree.inserer(6);
+ Btree.inserer(4);
+ Btree.inserer(5);
Btree.inserer(1);
+ Btree.inserer(0);
+
+ Btree.afficher();
+ Btree.afficher_arbre();
+
+ Btree.supprimer(4);
+
+ Btree.afficher();
+ Btree.afficher_arbre();
- String Btreeout = Btree.toString();
- System.out.println(Btreeout);
+ Btree.supprimer(6);
+ Btree.afficher();
+ Btree.afficher_arbre();
}
}