search - 如何在二叉树中找到给定深度的节点值的总和?

标签 search tree traversal

我已经为此挠头好几个小时了......

问题:

Binary Tree

   (0)      depth 0
   / \
  10   20   depth 1
 / \   / \
30 40  50 60  depth 2

我正在尝试编写一个函数,该函数将深度作为参数并返回给定深度的节点值的总和。

例如,如果我通过 2,它应该返回 180(即 30+40+50+60)

我决定使用广度优先搜索,当我找到所需深度的节点时,
总结值(value),但我就是不知道如何找出哪个节点在什么深度的方式。
但是通过这种方法,我觉得要走完全错误的方向。
function level_order($root, $targetDepth) {
$q = new Queue();
$q->enqueue($root);

while(!$q->isEmpty) {
    //how to determin the depth of the node???
    $node = $q->dequeue();

    if($currentDepth == $targetDepth) {
        $sum = $node->value;
    }

    if($node->left != null) {
        $q->enqueue($node->left);
    }
    if($node->right != null) {
        $q->enqueue($node->right);
    }
    //need to reset this somehow
    $currentDepth ++;
}

}

最佳答案

只需递归地进行深度优先搜索,保持当前级别并对给定深度的节点求和。

伪代码:

sum(Node, Level) = 
  if (Level == 0) return Node.value;
  else return f(Node.left, Level-1) + 
              f(Node.right, Level-1).

关于search - 如何在二叉树中找到给定深度的节点值的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3020070/

相关文章:

javascript - 将默认搜索文本添加到搜索框 html

algorithm - 2变量非线性搜索算法

algorithm - 在 scala 中使用 actors 进行二进制搜索?

jquery - 相当于 native javascript 中的 $(this)

javascript - 如何在 MarkLogic JSON 中搜索文件中特定路径处的键值?

jsf - Richfaces 树上的 ConcurrentModificationException

python - 未知的循环次数

algorithm - 将一棵二叉树分成 k 个大小相似的部分

java - 你什么时候决定为你的对象使用访问者?

c# - 为什么大多数时候只能向前遍历?