[英]Sum of nodes in a subtree (not binary)
I'm currently trying to find the sum of all nodes in a specified subtree.我目前正在尝试查找指定子树中所有节点的总和。 For example if I have a tree
例如,如果我有一棵树
A(5)
/ \
B(5) C(6)
/ / \
D(3) E(3) F(7)
|
G(1)
and I want to know the the sum(C)
, which should return 17.我想知道
sum(C)
,它应该返回 17。
This is the code I came up with using recursion, but I can't seem to reach a subtree which has more than 2 levels.这是我使用递归提出的代码,但我似乎无法达到超过 2 个级别的子树。 Eg my algorithm doesn't seem to reach G. I'm trying to get better at recursion, but I can't seem to fix this.
例如,我的算法似乎没有达到 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
You would be better with an improved interface and being able to lean on the features of collections:您会更好地使用改进的界面并能够依赖集合的功能:
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))
Output:输出:
17
The reason why your code appeared not to work, was that you were passing the previous key down to the next level of recursion.您的代码似乎不起作用的原因是您将前一个键向下传递到下一级递归。 However, your code seemed to recurse OK.
但是,您的代码似乎递归确定。 If you had added some
print(node.key)
you would have seen that you were visiting all the correct nodes.如果您添加了一些
print(node.key)
您会看到您正在访问所有正确的节点。
You can use recursion with sum
:您可以将递归与
sum
一起使用:
class Node:
def __init__(self, n, v, c=[]):
self.name, self.val, self.children = n, v, c
def get_sum(node):
return node.val+sum(map(get_sum, node.children))
tree = Node('A', 5, [Node('B', 5, [Node('D', 3)]), Node('C', 6, [Node('E', 3), Node('F', 7, [Node('G', 1)])])])
print(get_sum(tree.children[-1]))
Output:输出:
17
However, if you do not have access to the exact node C
, you can apply a simple search as part of the recursive function:但是,如果您无权访问确切的节点
C
,则可以应用简单搜索作为递归函数的一部分:
def get_sum(t, node):
def inner_sum(d, s=False):
return d.val*(s or d.name == t)+sum(inner_sum(i, s or d.name == t) for i in d.children)
return inner_sum(node)
print(get_sum('C', tree))
Output:输出:
17
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.