현재 DictionaryApp, BSTSet 및 BSTNode의 세 클래스가 있습니다. BSTSet과 BSTNode에 모두 메서드가 있습니다.이진 검색 트리 구현 - 메서드 포함
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;
}
}
내 문제는 BSTNode 클래스의 contains 메소드가 절대로 true를 반환하지 않으며 이유를 이해할 수 없다는 것입니다. 더 이상 내 코드를 보거나 더 이상 정보가 필요하면 언제든지 물어보십시오. 당신의 BSTNode
의 contains
방법에서
Contains는 compareTo 결과에서보다 큼을보고 적절한 방향으로 이동해야합니다. – spudone