Reputation: 1085
I currently have 3 classes - DictionaryApp, BSTSet and BSTNode - both the BSTSet and BSTNode have contains methods.
public class BSTSet <E extends Comparable<E>> extends AbstractSet <E> {
// the root of the supporting binary search tree
private BSTNode<E> root;
// number of elements in the set
private int count = 0;
public boolean isEmpty() {
return count == 0;
}
public boolean contains(E item) throws ClassCastException {
if(root == null) return false;
return root.contains(item);
}
public boolean add(E item) {
if (item == null)
throw new IllegalArgumentException("Null cannot be added to a BSTSet");
if(contains(item))return false;
if(root == null){
root = new BSTNode(item);
count++;
return true;
}else{
root.add(item);
count++;
return true;
}
}
}
public class BSTNode <E extends Comparable<E>> {
private E value;
private BSTNode<E> left;
public BSTNode<E> right;
public BSTNode(E value) {
this.value = value;
}
public E getValue() {
return value;
}
public BSTNode<E> getLeft() {
return left;
}
public BSTNode<E> getRight() {
return right;
}
public boolean contains(E item) {
if(item.compareTo(value) == 0) return true;
if(left != null) left.contains(item);
if(right != null) right.contains(item);
// no matching node was found
return false;
}
public boolean add(E item) {
if(item.compareTo(value) < 0) {left = new BSTNode(item); return true;}
if(item.compareTo(value) > 0) {right = new BSTNode(item); return true;}
return false;
}
}
My issues is that the contains method in the BSTNode class never returns true and I can't understand why. If you would like to see anymore of my code or need anymore information please feel free to ask.
Upvotes: 2
Views: 27411
Reputation: 178253
In your BSTNode
's contains
method, you are ignoring the results of calling contains
on left
and right
. If the child node found it, return true
immediately. Also, use the result of the comparison to determine which child to search next.
public boolean contains(E item) {
int comp = item.compareTo(value);
if(comp == 0) return true;
if(comp < 0 && left != null && left.contains(item)) return true;
if(comp > 0 && right != null && right.contains(item)) return true;
// no matching node was found
return false;
}
Your add
method ignores any child nodes that may already exist. Test for their presence first. If they don't exist, assign it as you are already doing. If they already exist, then call add
recursively on that child.
public boolean add(E item) {
if(item.compareTo(value) < 0) {
if (left == null) left = new BSTNode(item); return true;
else return left.add(item);
}
if(item.compareTo(value) > 0) {
if (right == null) right = new BSTNode(item); return true;
else return right.add(item);
}
return false;
}
Upvotes: 7