给出一个具有整数节点的n元树,如果任何负节点将总和重置为0,如何计算根到叶路径内的最大和。 例如,
-3
/ | \
2 4 1
/ \ |\ / | \
1 -1 1 2 2 -1 3
| | | \
5 -2 4 7
每个叶到节点路径内的最大和:
{-3,2,1} = 3
{-3,2,-1,5} = 5
{-3,4,1} = 5
{-3,4,2,-2} = 6
{-3,1,2} = 3
{-3,1,-1,4} = 4
{-3,1,-1,7} = 7
{-3,1,3} = 4
路径{-3,1,-1,7} = 7,将是给定条件下的最大总和
答案 0 :(得分:2)
import itertools
class Node(object):
"""Basic class to hold node state"""
def __init__(self, value, children=None):
self.value = value
self.children = list() if children is None else children
def dfs(node):
"""Generator that yields the depth-first paths of the tree"""
path = list()
def recurse(n):
path.append(n)
if not n.children:
yield path
for child in n.children:
for x in recurse(child):
yield x
path.pop()
for v in recurse(node):
yield path
# Iterate over the tree from the root node
for path in dfs(root):
max_path_value = 0
# Take the path and split it into groups of positive values
for valid, nodes in itertools.groupby(path, lambda n: n.value >= 0):
if valid:
path_value = sum(n.value for n in nodes)
if path_value > max_path_value:
max_path_value = path_value
path_str = ','.join(map(str, [n.value for n in path]))
print("{}: {}".format(path_str, max_path_value)
在您的树上运行它,给出以下输出,
-3,2,1: 3
-3,2,-1,5: 5
-3,4,1: 5
-3,4,2,-2: 6
-3,1,2: 3
-3,1,-1,4: 4
-3,1,-1,7: 7
-3,1,3: 4