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);