update: add remove recursiv

This commit is contained in:
Sobottasgithub 2026-02-09 08:43:49 +01:00
parent 86761e75b4
commit a97d9e0fa8
2 changed files with 42 additions and 13 deletions

View File

@ -38,6 +38,40 @@ public class BinaryTree {
}
}
public void remove(int value) {
rootNode = removeRecursiv(rootNode, value);
}
private Node removeRecursiv(Node root, int value) {
if (root == null) {
return null;
}
if (value < root.getContent()) {
root.setLeftNode(removeRecursiv(root.getLeftNode(), value));
} else if (value > root.getContent()) {
root.setRightNode(removeRecursiv(root.getRightNode(), value));
} else {
if (root.getLeftNode() == null) {
return root.getRightNode();
}
if (root.getRightNode() == null) {
return root.getLeftNode();
}
Node next = findMinimum(root.getRightNode());
root.setContent(next.getContent());
root.setRightNode(removeRecursiv(root.getRightNode(), next.getContent()));
}
return root;
}
private Node findMinimum(Node root) {
if (root.getLeftNode() == null) {
return root;
}
return findMinimum(root.getLeftNode());
}
public void insert(int content) {
if (rootNode == null) {
Node newNode = new Node(content);

View File

@ -15,20 +15,15 @@ public class Main {
System.out.println(binaryTree.search(42));
System.out.println(binaryTree.search(23));
System.out.println(binaryTree.search(22));
System.out.println(binaryTree.search(23));
System.out.println(binaryTree.search(55));
System.out.println(binaryTree.search(72));
System.out.println(binaryTree.search(1));
System.out.println(binaryTree.search(7));
System.out.println(binaryTree.search(3));
System.out.println(binaryTree.search(8));
System.out.println(binaryTree.search(16));
// Test values not in tree
System.out.println(binaryTree.search(2));
System.out.println(binaryTree.search(44));
System.out.println(binaryTree.search(100));
binaryTree.remove(23);
binaryTree.remove(1);
binaryTree.remove(9);
binaryTree.remove(72);
binaryTree.remove(42);
}
}