algorithm - 应该使用什么类型的遍历来找到二叉树的总和?

标签 algorithm binary-tree depth-first-search tree-traversal

以下问题出现在我的导师几年前的一次测试中。他提供了答案,但没有提供令人满意的解释。我用谷歌搜索了这个主题,但没有找到太多。我希望社区可以帮助我理解这个概念。

In order to find the sum of all of the integers in a binary tree, what type of traversal would be used?

(A) breadth-first
(B) depth-first in-order
(C) depth-first post-order
(D) depth-first pre-order

我的导师说答案是 (C) 深度优先后序,但我不明白为什么。看起来他们都会工作。如果您有任何见解,我将不胜感激。

谢谢。

编辑: 我终于明白为什么我的老师认为答案是 (C)。

如果您要在单个语句中编写一个带有 all 加法的求和函数,例如:

    int addup(Node n)
    {
        if (n == nil) return 0;
        return addup(n.left) + n.value + addup(n.right);
    }

无论总和中项的顺序如何,遍历都是后序的。这是因为这两个函数在加法发生之前首先被评估。然而,正如 Keith Randall 在他的回答中所展示的那样,强制执行预排序或有序遍历是微不足道的。

最佳答案

任何遍历顺序都可以,因为 sum 是关联的和对称的。例如,深度优先顺序:

int addup(Node n) {
    if (n == nil) return 0;
    int sum = addup(n.left);
    sum += n.value;
    sum += addup(n.right);
    return sum;
}

所有遍历都允许一个简单的求和实现。

关于algorithm - 应该使用什么类型的遍历来找到二叉树的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15103935/

相关文章:

algorithm - 游戏开发 : How to make my spritegame dynamic for resolutions?

algorithm - 卡在交叉线 - 算法

c - 为什么我们这里使用 "&"(: insert(&(*root)->left,值);但我们这里不使用 "&": search(root->left,值);

c - 二叉树 : user decides whether it should be a number tree or a word tree in c programming

graph-theory - DFS中的边缘分类

c++ - 使用分治法求一个数的n次方根

algorithm - 如何制作具有 6 个节点的完整二叉树?

c - 深度优先搜索代码不打印任何内容

time-complexity - 在具有 133 个节点和 737 个边的有向图上找到最大循环是否可计算?

algorithm - 使用加、减和减半计算三角根