这些是我的领域:
public class BSTSet <E> extends AbstractSet <E> {
// Data fields
private BSTNode root;
private int count = 0;
private Comparator<E> comp; // default comparator
/** Private class for the nodes.
* Has public fields so methods in BSTSet can access fields directly.
*/
private class BSTNode {
// Data fields
public E value;
public BSTNode left = null;
public BSTNode right = null;
// Constructor
public BSTNode(E v) {
value = v;
}
}
// Constructors - can either use a default comparator or provide one
public BSTSet() {
comp = new ComparableComparator(); // Declared below
}
public BSTSet(Comparator <E> c) {
comp = c;
}
// Methods
/** Return true iff the set is empty */
public boolean isEmpty() {
return count == 0;
}
/** Return the number of elements in set */
public int size() {
return count;
}
这是我正在尝试修复的方法:
/** Return true iff (if and only if) the set contains an item
* (the item must be non null)
*/
public boolean contains(Object item) {
// YOUR CODE HERE
//changes item to E so it can be used in the comparator
E value1 = (E) item;
if (root.value.equals(item)){
return true;
}
int s = comp.compare(value1,root.value);
if(s<0){
if (root.left == null)
return false;
else
return root.left.contains(item);
}
else if(s>0){
if (root.right == null)
return false;
else
return root.right.contains(item);
}
}
到目前为止,一切似乎都很顺利,但在 return root.left.contains(item); 时失败了并说它找不到符号 - 方法包含。我该如何解决这个问题,以便我可以运行 contains 方法,该方法应该返回该值是否在 BST 中?
最佳答案
left
和 right
都被声明为 BSTNode
实例。 BSTNode
没有名为 contains
的方法,因此您需要添加一个:
public boolean contains(Object item) {
return value.equals(item);
}
理想情况下,您希望节点和集合都实现相同的接口(interface),因此您不知道实际调用的是哪个实现。
关于java - 查找 BST 的方法仍然不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12781524/