[英]Maximum sum in a non-binary tree in Python
我有一棵非二叉树,该树的每个节点都有一个值。 我想获得最大的可用金额。 例如:
10
9 8 7
1 2 5 5 15
返回值是10 + 7 + 15 = 32我知道如果树是二叉树,该怎么做,但是如果树有n个分支怎么办? 这段代码是从该问题的第一个答案中提取的二进制代码: 在python中找到树的最大和
假设每个节点都有一个value
属性和一个children
属性,这些属性可以是子节点列表,空列表或无:
def tree_sum(node):
if node.children:
child_sums = []
for child in node.children:
child_sums.append(tree_sum(child) + node.value)
return max(child_sums)
else:
return node.value
print tree_sum(root)
这是一种方法:
class Node:
def __init__(self, value):
self.value = value
self.children = []
def max_sum(root):
if len(root.children) == 0:
return root.value
sums = []
for child in root.children:
sums.append(root.value + max_sum(child))
return max(sums)
n_9 = Node(9)
n_9.children.extend([Node(1), Node(2), Node(5)])
n_8 = Node(8)
n_8.children.extend([Node(5)])
n_7 = Node(7)
n_7.children.extend([Node(15)])
n_10 = Node(10)
n_10.children = [n_9, n_8, n_7]
print max_sum(n_10)
# Output: 32
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.