compareTo method in a Binary Sorted Tree

I'm trying to have a method that counts the number of elements in a BST that are greater than x: if tree contains {3, 7, 8, -4, 6}, and x = 6, method should return 2.

At the moment, I'm getting a cannot find symbol error for my compareTo... this is my code:

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));
}

Upvotes: 1

Views: 231

Answers (2)

Mạnh Quyết Nguyễn
Mạnh Quyết Nguyễn

Reputation: 18235

compareTo is a method from Comparable interface.

To use that you should define that your class is implement Comparable interface

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

} 

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727077

You need to let Java compiler know that T has a compareTo method by specifying a type constraint:

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

Upvotes: 3

Related Questions