java - 查找树中的最大元素

标签 java data-structures

我有一个二叉树,它以这种方式实现节点:

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/

相关文章:

java - 具有未知对象结构的标准根元素的遍历路径

data-structures - 用于创建计算机科学图表的软件/Webapp

c# - 索引大文件的数据结构

algorithm - 在特殊条件下获取集合中的最大数量

c# - 使用 2 维时,R 树能否保持 z 顺序?

Java XPath API 引用

java - 加载 Sprite 表时出现问题

java - J2Objc Eclipse 插件 "error: --ignore-missing-imports is no longer supported"

java - 使用 jetty 构建 docker 镜像 - 我应该什么时候构建?

c++ - 二进制最大堆时间复杂度