c++ - 将军树高度

标签 c++ algorithm data-structures tree big-o

我正在做 Tamassia 和 Goodrich 的 C++ 数据结构和算法(第 2 版)

我无法理解一般树 T 高度的运行时间为 O(n + sum_over_p(1 + dp)) 其中 n 是 T 的节点数,dp 是节点 p 的深度(第 276 页) .

这里使用的概念是“树的高度是外部节点的最大深度”

这是书中给出的求树高的代码

int height1(const Tree& T) {
    int h = 0;
    PositionList nodes = T.positions(); // list of all nodes
    for (Iterator q = nodes.begin(); q != nodes.end(); ++q) { 
        if (q−>isExternal())
            h = max(h, depth(T, *q)); // get max depth among leaves
    }
    return h;
}

谢谢!!

更新

深度函数的代码是

int depth(const Tree& T, const Position& p) {
    if (p.isRoot())
        return 0; // root has depth 0
    else
        return 1 + depth(T, p.parent()); // 1 + (depth of parent)
}

最佳答案

按照我的理解,您遍历树中的所有节点是 O(n)。 对于每个外部节点,您调用 depth 函数,它采用 O(1+dp)(因为对于深度为 0 的根节点,它需要 1 次函数调用,因此是 1+dp),所以这是sum_over_p(1 + dp) 的原因。

唯一的问题是,在代码中他们只为外部节点运行 depth 而在定义中他们似乎为每个节点调用它......所以我不确定哪里错了.

关于c++ - 将军树高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28124760/

相关文章:

algorithm - 测试点是否在圆内的方程

ruby - 学习编程

c++ - 在 C++ 中重载 [] 运算符

arrays - Lua的混合数组和哈希表;它存在于其他任何地方吗?

c++ - 有没有办法将类嵌入到同名的新命名空间中?

c++ - 将 MFnParticleSystem 添加到代码时,Maya 应用程序代码将无法编译

c++ - 如何制作不需要用户使用特定版本的 Visual Studio 的 C++ API?

c++ - Pthread + Visual Studio 2013 编译错误

algorithm - 在不同区间内找到共同点

c++ - 从连续的单词序列中提取任意范围的位的最有效方法是什么?