115 lines
2.9 KiB
Java
115 lines
2.9 KiB
Java
public class BinaryTree {
|
|
private Node rootNode = null;
|
|
|
|
public BinaryTree() {}
|
|
|
|
public BinaryTree(int content) {
|
|
insert(content);
|
|
}
|
|
|
|
public boolean search(int value) {
|
|
if (rootNode == null) {
|
|
return false;
|
|
}
|
|
|
|
return searchRecursiv(rootNode, value);
|
|
}
|
|
|
|
private boolean searchRecursiv(Node node, int value) {
|
|
int content = node.getContent();
|
|
|
|
if (value == content) {
|
|
return true;
|
|
} else if (value > content) {
|
|
Node leftNode = node.getLeftNode();
|
|
if (leftNode == null) {
|
|
return false;
|
|
}
|
|
return searchRecursiv(leftNode, value);
|
|
} else if (value < content) {
|
|
Node rightNode = node.getRightNode();
|
|
if (rightNode == null) {
|
|
return false;
|
|
}
|
|
return searchRecursiv(rightNode, value);
|
|
} else {
|
|
System.out.println("Something went wrong!");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
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);
|
|
rootNode = newNode;
|
|
} else {
|
|
insertRecursiv(rootNode, content);
|
|
}
|
|
}
|
|
|
|
private void insertRecursiv(Node currentNode, int content) {
|
|
int currentContent = currentNode.getContent();
|
|
|
|
// has to be inserted left
|
|
if (currentContent <= content) {
|
|
// if node == null -> insert left
|
|
if (currentNode.getLeftNode() == null) {
|
|
Node newNode = new Node(content);
|
|
currentNode.setLeftNode(newNode);
|
|
System.out.println("Inserted Left");
|
|
return;
|
|
} else {
|
|
// traverse -> 1 down
|
|
insertRecursiv(currentNode.getLeftNode(), content);
|
|
return;
|
|
}
|
|
} else /* insert right */ {
|
|
// if node == null -> insert right
|
|
if (currentNode.getRightNode() == null) {
|
|
Node newNode = new Node(content);
|
|
currentNode.setRightNode(newNode);
|
|
System.out.println("Inserted Right");
|
|
return;
|
|
} else {
|
|
// traverse -> 1 down
|
|
insertRecursiv(currentNode.getRightNode(), content);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
}
|