BAEL -1339 Implement a binary tree in Java (#3301)

* edge cases binary tree

* code cleanup
This commit is contained in:
Marcos Lopez Gonzalez 2017-12-28 13:16:38 +01:00 committed by Grzegorz Piwowarek
parent 0a76081ac3
commit 5e25e2c3ea
2 changed files with 55 additions and 12 deletions

View File

@ -8,15 +8,7 @@ public class BinaryTree {
Node root;
public void add(int value) {
Node newNode = new Node(value);
if (root == null) {
root = newNode;
return;
}
addRecursive(root, value);
root = addRecursive(root, value);
}
private Node addRecursive(Node current, int value) {
@ -27,18 +19,32 @@ public class BinaryTree {
if (value < current.value) {
current.left = addRecursive(current.left, value);
} else {
} else if (value > current.value) {
current.right = addRecursive(current.right, value);
} else {
// value already exists
return current;
}
return current;
}
public boolean isEmpty() {
return root == null;
}
public int getSize() {
return getSizeRecursive(root);
}
private int getSizeRecursive(Node current) {
if (current == null) {
return 0;
}
return getSizeRecursive(current.left) + 1 + getSizeRecursive(current.right);
}
public boolean containsNode(int value) {
return containsNodeRecursive(root, value);
}
@ -125,12 +131,15 @@ public class BinaryTree {
if (node != null) {
traversePostOrder(node.left);
traversePostOrder(node.right);
System.out.print(" " + node.value);
}
}
public void traverseLevelOrder() {
if (root == null) {
return;
}
Queue<Node> nodes = new LinkedList<>();
nodes.add(root);

View File

@ -1,5 +1,6 @@
package com.baeldung.tree;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@ -26,6 +27,26 @@ public class BinaryTreeTest {
assertFalse(bt.containsNode(1));
}
@Test
public void givenABinaryTree_WhenAddingExistingElement_ThenElementIsNotAdded() {
BinaryTree bt = createBinaryTree();
int initialSize = bt.getSize();
assertTrue(bt.containsNode(3));
bt.add(3);
assertEquals(initialSize, bt.getSize());
}
@Test
public void givenABinaryTree_WhenLookingForNonExistingElement_ThenReturnsFalse() {
BinaryTree bt = createBinaryTree();
assertFalse(bt.containsNode(99));
}
@Test
public void givenABinaryTree_WhenDeletingElements_ThenTreeDoesNotContainThoseElements() {
@ -36,6 +57,19 @@ public class BinaryTreeTest {
assertFalse(bt.containsNode(9));
}
@Test
public void givenABinaryTree_WhenDeletingNonExistingElement_ThenTreeDoesNotDelete() {
BinaryTree bt = createBinaryTree();
int initialSize = bt.getSize();
assertFalse(bt.containsNode(99));
bt.delete(99);
assertFalse(bt.containsNode(99));
assertEquals(initialSize, bt.getSize());
}
@Test
public void givenABinaryTree_WhenTraversingInOrder_ThenPrintValues() {