The implementation violates a requirement of a Binary Search Tree: it will add duplicate elements. You can fixLet's expose this bug by adding a unit test:
@Test
public void testNoDups() {
CreateBinarySearchTree tree = new CreateBinarySearchTree();
tree.add(4, 4);
tree.add(4);
assertEquals("[null,4,null]", tree.toString());
}
Easy enough to fix, by adding an else in the main loop:
while (true) {
if (item < node.item) {
if (node.left == null) {
node.left = new TreeNode(null, item, null);
break;
}
node = node.left;
} else if (item > node.item) {
if (node.right == null) {
node.right = new TreeNode(null, item, null);
break;
}
node = node.right;
} else {
break;
}
}
And while at it let's add a unit test for this too:
@Test
public void testNoDups() {
CreateBinarySearchTree tree = new CreateBinarySearchTree();
tree.add(4, 4);
tree.add(4);
assertEquals("[null,4,null]", tree.toString());
}
Instead of a while loop, it'sit would be more elegant to implement adding a node using recursion:
The constructor that takes an array calls this(), but since thethat other constructor does nothing, this is pointless. The variable names a and i are poor, it would be better to rename athem to arr or items, and i to item, respectively.
As others have pointed out, it would be bettermake sense to move the adding logic outside of the constructor, so that callers could benefit from it too. In fact, how about removing all thosethe constructors, and addingusing this new method instead to add elements: