java - 获取具有多个 child 的树的高度

标签 java

我很难完成这个算法来找到具有多个子节点(非二元)的树的高度。

有人知道哪里出了问题吗?

private int getHeight(Node<T> root, int height, int result){

        if (root.getChildren().size()==0) {
            return height;
        }
        height++;

        //Iterate every child
        for (Node<T> childNode  : root.getChildren()) {

            //Get the height again
            height =getHeight(childNode, height, result);

            //Update if new high result
            if (height>result) {
                result = height;
            }

            height = 0;
        }

        //Return highest point
        return result;
    }

最佳答案

添加高度和结果参数会使事情变得更加困难。

在函数中,找到每个 child 的高度。保留最大的。返回 1 + 最大的高度。

像这样的东西(未经测试,未编译):

private int getHeight(Node<T> root){

    int max = 0;
    for (Node<T> childNode  : root.getChildren()) {
        int height = getHeight(childNode);
        if (height > max)
            max = height;
    }
    return max + 1;
}

关于java - 获取具有多个 child 的树的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18797547/

相关文章:

java - 我的 try catch 循环陷入无限循环,每次都应该提示用户输入

java - 设置 Elasticsearch 问题

java - 有没有办法将电话号码标准化为 1-222-444-5555(根据北美标准)?

java - 在 HashMap 值对象上同步

java - 基于文本的 Java 游戏将变量传递给另一个类

java - 将属性文件或 xml 文件中的属性值注入(inject) PreAuthorize(...) java 注释(未解决)

java - 实现固定大小的 HashMap

Java - 按字节下载图像下载损坏的图像

java反射superClass被hibernate加载的问题

java - 较小的方法