https://slides.com/d/klgllCM/live
Beispiel
BinarySearchTree.java
/**
* A class representing a Binary Search Tree (BST).
*/
public class BinarySearchTree {
/**
* Inserts a value into the binary search tree.
*
* @param value The value to be inserted.
*/
public void insert(int value) {
// TODO: Implement the insert method
}
/**
* Searches for a value in the binary search tree.
*
* @param value The value to search for.
* @return true if the value is found, false otherwise.
*/
public boolean search(int value) {
// TODO: Implement the search method
return false;
}
}
BinarySearchTreeTest.java
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class BinarySearchTreeTest {
@Test
public void testInsertAndSearch() {
BinarySearchTree bst = new BinarySearchTree();
// Insert values into the BST
bst.insert(50);
bst.insert(30);
bst.insert(20);
bst.insert(40);
bst.insert(70);
bst.insert(60);
bst.insert(80);
// Test searching for values
assertTrue(bst.search(50), "The value 50 should be found in the tree.");
assertTrue(bst.search(30), "The value 30 should be found in the tree.");
assertTrue(bst.search(20), "The value 20 should be found in the tree.");
assertTrue(bst.search(40), "The value 40 should be found in the tree.");
assertTrue(bst.search(70), "The value 70 should be found in the tree.");
assertTrue(bst.search(60), "The value 60 should be found in the tree.");
assertTrue(bst.search(80), "The value 80 should be found in the tree.");
// Test searching for non-existent values
assertFalse(bst.search(90),
"The value 90 should not be found in the tree.");
assertFalse(bst.search(15),
"The value 15 should not be found in the tree.");
}
}
private class Node {
int value;
Node left, right;
Node(int item) {
value = item;
left = right = null;
}
}
Do it now!
BinarySearchTree.java
(Implementierung)public class BinarySearchTree {
private class Node {
int value;
Node left, right;
Node(int item) {
value = item;
left = right = null;
}
}
private Node root;
public void insert(int value) {
root = insertRec(root, value);
}
//...
}
BinarySearchTree.java
(Implementierung)public class BinarySearchTree {
//...
private Node insertRec(Node root, int value) {
if (root == null) {
root = new Node(value);
return root;
}
if (value < root.value) {
root.left = insertRec(root.left, value);
} else if (value > root.value) {
root.right = insertRec(root.right, value);
}
return root;
}
public boolean search(int value) {
return searchRec(root, value);
}
//...
}
BinarySearchTree.java
(Implementierung)public class BinarySearchTree {
//...
public boolean search(int value) {
return searchRec(root, value);
}
private boolean searchRec(Node root, int value) {
if (root == null) {
return false;
}
if (root.value == value) {
return true;
}
if (value < root.value) {
return searchRec(root.left, value);
}
return searchRec(root.right, value);
}
}
"Ein guter Test ist einer, der einen Fehler findet. Ein großartiger Test ist einer, der viele Fehler findet." — Boris Beizer