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