diff --git a/BinaryTree.java b/BinaryTree.java index 779b145..98d9c2e 100644 --- a/BinaryTree.java +++ b/BinaryTree.java @@ -38,6 +38,40 @@ public class BinaryTree { } } + 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); diff --git a/Main.java b/Main.java index c960159..44489fe 100644 --- a/Main.java +++ b/Main.java @@ -15,20 +15,15 @@ public class Main { System.out.println(binaryTree.search(42)); - System.out.println(binaryTree.search(23)); - System.out.println(binaryTree.search(22)); - System.out.println(binaryTree.search(23)); - System.out.println(binaryTree.search(55)); - System.out.println(binaryTree.search(72)); - System.out.println(binaryTree.search(1)); - System.out.println(binaryTree.search(7)); - System.out.println(binaryTree.search(3)); - System.out.println(binaryTree.search(8)); - System.out.println(binaryTree.search(16)); - // Test values not in tree System.out.println(binaryTree.search(2)); - System.out.println(binaryTree.search(44)); - System.out.println(binaryTree.search(100)); + + binaryTree.remove(23); + binaryTree.remove(1); + binaryTree.remove(9); + binaryTree.remove(72); + binaryTree.remove(42); + + } }