update: add remove recursiv
This commit is contained in:
parent
86761e75b4
commit
a97d9e0fa8
@ -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);
|
||||
|
||||
21
Main.java
21
Main.java
@ -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);
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user