81 lines
2.0 KiB
Java
81 lines
2.0 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 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;
|
|
}
|
|
}
|
|
}
|
|
}
|