forked from pr2-lecture/examples
67 lines
1.2 KiB
Java
67 lines
1.2 KiB
Java
package pr2.datenstrukturen.bt;
|
|
|
|
class Node {
|
|
int data;
|
|
Node left;
|
|
Node right;
|
|
|
|
public Node(int item) {
|
|
data = item;
|
|
left = right = null;
|
|
}
|
|
}
|
|
|
|
public class BinaryTree {
|
|
// Wurzel des Baums
|
|
Node root;
|
|
|
|
public BinaryTree() {
|
|
root = null;
|
|
}
|
|
|
|
public void insert(int key) {
|
|
root = insertRec(root, key);
|
|
}
|
|
|
|
private Node insertRec(Node root, int key) {
|
|
|
|
if (root == null) {
|
|
root = new Node(key);
|
|
return root;
|
|
}
|
|
|
|
if (key < root.data)
|
|
root.left = insertRec(root.left, key);
|
|
else if (key > root.data)
|
|
root.right = insertRec(root.right, key);
|
|
|
|
return root;
|
|
}
|
|
|
|
public void inorder() {
|
|
inorderRec(root);
|
|
}
|
|
|
|
void inorderRec(Node root) {
|
|
if (root != null) {
|
|
inorderRec(root.left);
|
|
System.out.println(root.data);
|
|
inorderRec(root.right);
|
|
}
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
BinaryTree tree = new BinaryTree();
|
|
|
|
tree.insert(50);
|
|
tree.insert(30);
|
|
tree.insert(20);
|
|
tree.insert(40);
|
|
tree.insert(70);
|
|
tree.insert(60);
|
|
tree.insert(80);
|
|
|
|
tree.inorder();
|
|
}
|
|
}
|