I have a class assignment where I need to sort a target into a binary tree node, where given a root, I need to compare it with the root, and put the target as a left child if the target is less than the value of the root, or put the target as a right child if the target is greater than the value of the root.
I have to use the method header and arguments as given, and I have written my code in like so:
public static boolean find(TreeNode t, Comparable x)
{
TreeNode p = t;
if(t == null)
return false;
while(p != null)
{
if(p.getValue() == x)
return true;
else if(p.getValue() < x)
p = p.getLeft();
else
p = p.getRight();
}
return false;
}
which returns this error:
BinarySearchTree.java:109: error: bad operand types for binary operator '<'
I have also tried the compareTo method, by trying something along the likes of
if(p.getValue().compareTo(x) == 0)
return true;
which returns the error below:
BinarySearchTree.java:107: error: cannot find symbol if(p.getValue().compareTo(x)) ^ symbol: method compareTo(Comparable) location: class Object
How can I fix this error? I tried to search this problem up, but that wasn't particularly helpful.
UPDATE—TreeNode Class:
class TreeNode
{
private Object value;
private TreeNode left, right;
public TreeNode(Object initValue)
{
value = initValue;
left = null;
right = null;
}
public TreeNode(Object initValue, TreeNode initLeft, TreeNode initRight)
{
value = initValue;
left = initLeft;
right = initRight;
}
public Object getValue()
{
return value;
}
public TreeNode getLeft()
{
return left;
}
public TreeNode getRight()
{
return right;
}
public void setValue(Object theNewValue)
{
value = theNewValue;
}
public void setLeft(TreeNode theNewLeft)
{
left = theNewLeft;
}
public void setRight(TreeNode theNewRight)
{
right = theNewRight;
}
}
Looks like x
is your Comparable
interface. You should call the compareTo
method on this parameter, and then compare the result with 0
. The Comparable Javadoc has some usage examples. The compareTo
function returns:
a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
The reason you get your errors is that, at first, you were trying to apply the <
on incompatible types. p.getValue()
returns you an Object
, while x
is a Comparable
(usually you should apply this operator on primitives, like int
, long
, etc.).
The second error was that, even if p.getValue()
object has a compareTo
method, you must be careful against which other object you compare to. For example, if it's a String, you can compare it only against another String, e.g., "str1".compareTo("str2");
In order to correctly compare your values, you should do something like:
// checking if x is less than p's value
if (x.compareTo(p.getValue()) < 0) { ... }
// checking if x is greater than p's value
if (x.compareTo(p.getValue()) > 0) { ... }
// checking if x is equal to p's value
if (x.compareTo(p.getValue()) == 0) { ... }