python - 子树中的节点总和(非二叉树)

标签 python recursion tree

我当前正在尝试查找指定子树中所有节点的总和。例如,如果我有一棵树

     A(5)
     / \
   B(5) C(6)
   /    /  \
  D(3) E(3) F(7)
            |
            G(1)

我想知道 sum(C),它应该返回 17。

这是我使用递归想出的代码,但我似乎无法到达具有超过 2 层的子树。例如。我的算法似乎没有达到 G。我试图在递归方面做得更好,但我似乎无法解决这个问题。

def navigate_tree(node,key): #node of the root of subtree, along with its key
    children = node.get_children()
    if (len(children) ==0):
        return node.key
    else:
        for child in children: #not a binary tree so trying to loop through siblings
            key += navigate_tree(child,key) #summing up key recursively
        return key 

最佳答案

改进的界面并能够利用集合的功能会更好:

def navigate_tree(node): 
    children = node.get_children()
    key = node.key
    for child in children:
        key += navigate_tree(child)
    return key

# class Node and data A..G elided
print(navigate_tree(C))

输出:

17

您的代码似乎不起作用的原因是您将前一个键传递到下一个递归级别。但是,您的代码似乎递归正常。如果您添加了一些print(node.key),您就会发现您正在访问所有正确的节点。

关于python - 子树中的节点总和(非二叉树),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60720513/

相关文章:

Python 在列表中添加具有相同键的字典值

python - 将递归问题代码从 Python 转换为 Common Lisp

c# - int ref 参数是否被装箱?

haskell - 如何使免费的 monad 解释器递归?

java - 使用 JAVA Swing 的可点击树 UI?

c++ - 后继AVL树c++

mysql - MySQL 中的版本控制树结构

python - 使用 python unittest,我如何断言报告的错误给出了特定消息?

python - 条件约束

python - 如何在 pandas 中转换 json 对象数组