I'm trying to find the minimum value of a node within a tree, and in order to detect whether something has smaller value, I'm using the compareTo()
function as seen below:
@SuppressWarnings("unchecked")
public static Object min(TreeNode t)
{
if(t == null) {
return null;
}
Comparable<TreeNode> min = (Comparable<TreeNode>) t;
if(t.getLeft() != null) {
Comparable<TreeNode> leftMin = (Comparable<TreeNode>) min(t.getLeft());
if( ((Comparable<TreeNode>)leftMin).compareTo( (Comparable<TreeNode>)min) < 0) {
min = leftMin;
}
}
if(t.getRight() != null) {
Comparable<TreeNode> rightMin = (Comparable<TreeNode>) min(t.getRight());
if( ((Comparable<TreeNode>)rightMin).compareTo( (Comparable<TreeNode>)min) < 0) {
min = rightMin;
}
}
return min;
}
However, I'm receiving the following error:
error: incompatible types: Comparable<TreeNode> cannot be converted to TreeNode
at the if statement.
I was told that the Object must be cast to Comparable in order to call compareTo()
And I have tried looking at this similiar question, but I don't have access to change the TreeNode Class
TreeNode Class:
public class TreeNode
{
private Object value;
private TreeNode left, right;
public TreeNode(Object initValue)
{
value = initValue;
left = null;
right = null;
}
/*methods*/
}
And I have also tried: if(leftMin.compareTo(min) < 0)
however that yields the same error.
Do you know how to properly cast and convert the following classes?