Python中非二叉树中的最大总和

时间:2016-07-06 00:24:07

标签: python recursion tree

我有一个非二叉树,该树的每个节点都有一个值。我想得到最大数额。 例如:

              10
       9       8      7
    1  2  5     5      15

回报将是10 + 7 + 15 = 32 如果树是二进制的,我知道如何做到这一点,但如果树有n个分支怎么办? 此代码是从此问题的第一个答案中获取的二进制代码:Find the maximum sum of a tree in python

2 个答案:

答案 0 :(得分:3)

假设每个节点都有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)

答案 1 :(得分:0)

这是一种方法:

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