50 lines
1.3 KiB
Java
50 lines
1.3 KiB
Java
public class BinaryTree {
|
|
private Node rootNode = null;
|
|
|
|
public BinaryTree() {}
|
|
|
|
public BinaryTree(int content) {
|
|
insert(content);
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|
|
}
|
|
}
|