【问题标题】:compareTo method in a Binary Sorted Tree二进制排序树中的 compareTo 方法
【发布时间】:2018-05-07 17:46:12
【问题描述】:

我正在尝试使用一种方法来计算 BST 中大于 x 的元素数量:如果树包含 {3, 7, 8, -4, 6}x = 6,则方法应为 return 2

目前,我的 compareTo 出现找不到符号错误...这是我的代码:

public int countGreater(T x)
{
    BSTNode<T> base = root;
    if(base == null) return 0;
    int greater = great(base, x);
    return greater;
}

private int great(BSTNode<T> base, T x)
{
    int numG = 0;
    Iterator<T> getGreatest = getIterator(Postorder);

    while(getGreatest.hasNext())
    {
        if(compare(getGreatest.next(), x) > 0)
        {
            numG++;
        }
    }

    return numG;
}

public int compare(T a, T b)
{
    return (a.compareTo(b));
}

【问题讨论】:

  • T 是如何定义的?
  • 您的T 是否定义为Comparable 本身?

标签: java compare binary-tree compareto


【解决方案1】:

你需要通过指定类型约束让Java编译器知道T有一个compareTo方法:

class MyBst<T extends Comparable<? super T>> {
    ... //    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ... //         Add this constraint
}

【讨论】:

    【解决方案2】:

    compareTo 是来自Comparable 接口的方法。

    要使用它,你应该定义你的类是实现 Comparable 接口

    private <T extends Comparable<T>> int(BSTNode<T> base, T x) {
    
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-21
      • 2020-11-05
      • 1970-01-01
      • 2012-08-20
      • 2012-11-25
      • 1970-01-01
      相关资源
      最近更新 更多