java - 查找 BST 的方法仍然不起作用

标签 java binary-search-tree

这些是我的领域:

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 中?

最佳答案

leftright 都被声明为 BSTNode 实例。 BSTNode 没有名为 contains 的方法,因此您需要添加一个:

public boolean contains(Object item) {
    return value.equals(item);
}

理想情况下,您希望节点和集合都实现相同的接口(interface),因此您不知道实际调用的是哪个实现。

关于java - 查找 BST 的方法仍然不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12781524/

相关文章:

Java-重写泛型接口(interface)方法时如何获取具体参数类型

Java Socket RPC 协议(protocol)

java - 创建格式为 "yyyy-mm-dd"的变量 Date

java - 从 Json 响应中转义\n和\"

C语言: Error in implementing binary search tree using structures

python - 在 Python 中将值插入二叉搜索树

java - 打开 .java 文件并像在 Eclipse 的控制台中一样运行的程序

c++ - 二叉树递归加法没有产生正确的结果

algorithm - 是否总是可以使用至多 O(n) 树旋转将一个 BST 转换为另一个?

java - 未排序数组到二叉搜索树