For class I need to create my own binary search tree implementation including a search,add, remove and toString method but I cannot try those methods without add first. I am not allowed to write or use a node class. Each node of my tree is supposed to be an instance of the BinarySearchTree class. I cannot figure out how to traverse the tree without the typical nodes. Here's my first portion of code:
public class BinarySearchTree<E extends Comparable<E>> implements BinarySearchTreeInterface<E> {
E value;
BinarySearchTree<E> parent;
BinarySearchTree<E> left;
BinarySearchTree<E> right;
static String draw;
public BinarySearchTree() {
value = null;
parent = null;
left = null;
right = null;
}
@Override
public void add(E item) {
if (isRoot() && value == null) {
value = item;
} else if (value.compareTo(item) > 0) {
if (right != null) {
add(right.value);
} else {
BinarySearchTree<E> newNode = new BinarySearchTree<E>();
newNode.value = item;
newNode.right = newNode;
}
}else if (value.compareTo(item) < 0) {
if (left != null) {
add(left.value);
}
} else {
BinarySearchTree<E> newNode = new BinarySearchTree<E>();
newNode.value = item;
newNode.left = newNode;
}
}
This seems to only add the root value of 5. I believe it has something to do with not connecting the new "node" to the parent or maybe my constructor. I am struggling to traverse the tree and connect the "nodes" without using a node class.