c++ - 普通树 - 非二叉树 - 高度

标签 c++ tree height

抱歉我的英语不好。这不是我的母语。

我的问题是我想知道一棵普通树的高度,我不知道它的英文是不是这么称呼。

树的结构是:

struct GTnode{
    int data;
    nodeGT *fc; //first child
    nodeGT *nb; //next brother
}

接下来的每个兄弟都与第一个 child 处于同一级别,并且每个第一个 child 都有+1级别。

这是我的代码,但我不确定是否正确:

int height(GT *root){
    if(root == null){
        return 0;
    }
    else{
        int max=0;
        int h;
        h = height(root->fc);
        if(h > max){
            max = h;
        }
        max = max + 1;
        h = height(root->nb);
        if(h > max){
           max = h;
        }
        return max;
    }
}

最佳答案

你的代码看起来没问题。我只是让它更紧凑一点:

#include <algorithm>

int height(GT *root) {
    return root ? std::max(height(root->fc) + 1, height(root->nb)) : 0;
}

关于c++ - 普通树 - 非二叉树 - 高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25797604/

相关文章:

html - 如何在具有灵活高度的html css中嵌入Google Form iframe(响应式)

c++ - 使用 std::set 替代 BOOST_FOREACH?

c++ - 如何处理可能指向内部数据的引用参数?

c++ - 使用成员变量的地址作为ID

javascript - 创建没有任何父级的树结构作为一级对象列表的输入

python gui树走

javascript - 均衡容器行上的 div 高度

C++ 在构造函数中通过引用传递对象和复制构造函数混淆

algorithm - 最坏情况二分查找?

html - 坚持 HTML block 的响应高度