algorithm - 如何计算一棵树的高度

标签 algorithm data-structures tree

我正在尝试学习 DSA,但遇到了一个问题。

如何计算树的高度。我的意思是普通树,而不是像 BT 或 BST 这样的树的任何特定实现。

我试过谷歌,但似乎每个人都在谈论二叉树,而普通树没有任何可用的东西。

谁能帮我重定向到某些页面或文章来计算树的高度。

最佳答案

假设树中的一个典型节点表示为 Java 类。

class Node{
    Entry entry;
    ArrayList<Node> children;
    Node(Entry entry, ArrayList<Node> children){
        this.entry = entry;
        this.children = children;
    }   
    ArrayList<Node> getChildren(){
        return children;
    }   
}  

然后一个简单的高度函数可以是 -

int getHeight(Node node){
    if(node == null){
        return 0;
    }else if(node.getChildren() == null){
        return 1;
    } else{
       int childrenMaxHeight = 0;
       for(Node n : node.getChildren()){
           childrenMaxHeight = Math.max(childrenMaxHeight, getHeight(n));
       }
       return 1 + childrenMaxHeight;
    }
}

然后你只需要调用这个函数传递树的根作为参数。由于它恰好遍历所有节点一次,因此运行时间为 O(n)。

关于algorithm - 如何计算一棵树的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42269698/

相关文章:

java - 使用链表代码实现Queue返回空指针异常

php - PHP 5.x是否具有某种HashSet或Set类?

c - Trie树结构声明

algorithm - 检查一棵树是否是镜像?

c - 如何从 C 级代码访问 Ruby AST?

java - 哪个更快?(来自CTCI书)

algorithm - 如何有效地解决矩阵可达性递归问题?

WEKA J48 类的 C# 或 .NET 实现?

algorithm - 为什么这个指数在这个例子中以这种方式计算?

algorithm - 如何在 id 序列中有效地重用已发布的 id