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

mas*_*san 2 tree search traversal

为此,我一直在摸不着头几个小时......

问题:

Binary Tree

   (0)      depth 0
   / \
  10   20   depth 1
 / \   / \
30 40  50 60  depth 2
Run Code Online (Sandbox Code Playgroud)

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

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

我决定使用呼吸优先搜索,当我找到具有所需深度的节点时,总结该值,但我无法弄清楚如何找出哪个节点处于什么深度的方式.但是通过这种方法我觉得完全错误的方向.

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 ++;
}
Run Code Online (Sandbox Code Playgroud)

}

Igo*_*kon 9

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

伪代码:

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