我有一个二叉树,它以这种方式实现节点:
public class BinaryTreeNode<T>
{
T element;
BinaryTreeNode<T> leftChild; // left subtree
BinaryTreeNode<T> rightChild; // right subtree
}
我正在尝试搜索树中保存的最大值,但我未能创建一个成功的方法来实现此目的。这是我尝试过的:
public void maxElement(Method visit)
{
ArrayList<T> a = new ArrayList<>();
BinaryTreeNode<T> b = root;
while(b != null)
{
try
{
visit.invoke(null, b); //This visit Method is to traverse the nodes
}
catch(Exception e)
{
System.out.println(e);
}
if(b.leftChild != null)
a.add(b.leftChild.element);
if(b.rightChild != null)
a.add(b.rightChild.element);
Collections.sort(a); //Here is where it fails
System.out.println(a.get(0));
}
}
这是 IDE 抛出的错误:
Bound mismatch: The generic method sort(List) of type Collections is not applicable for the arguments (ArrayList). The inferred type T is not a valid substitute for the bounded parameter
我知道我无法对泛型类型进行排序,但不知道如何实现我想要的。
最佳答案
如果 T
预计是支持比较的类型,那么您应该声明
public class BinaryTreeNode<T extends Comparable<T>> {
您应该将其理解为“T 类型的对象必须与 T 类型的其他对象进行比较。”
关于java - 查找树中的最大元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19867783/