gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:23:46 25 4
gpt4 key购买 nike

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

     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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com