简体   繁体   English

如果负节点重新启动总和,则查找树中从根到n元叶的最大路径总和

[英]Finding the maximum path sum from root to n-ary leaf in a tree if a negative node restarts the sum from 0

Given a n-ary tree with integer nodes, how to calculate the maximum sum inside a root to leaf path if any negative node resets the sum to 0. For eg., 给定一棵具有整数节点的n元树,如果有任何负节点将总和重置为0,如何计算根到叶路径内的最大和。

      -3
    /  |   \
  2    4      1
 / \   |\    / | \
1  -1  1 2  2 -1   3
    |    |     | \
    5   -2     4  7

Maximum sum inside each leaf to node path: 每个叶到节点路径内的最大和:

{-3, 2, 1} = 3 {-3,2,1} = 3

{-3, 2, -1, 5} = 5 {-3,2,-1,5} = 5

{-3, 4, 1} = 5 {-3,4,1} = 5

{-3, 4, 2, -2} = 6 {-3,4,2,-2} = 6

{-3, 1, 2} = 3 {-3,1,2} = 3

{-3, 1, -1 ,4} = 4 {-3,1,-1,4} = 4

{-3, 1, -1 ,7} = 7 {-3,1,-1,7} = 7

{-3, 1, 3} = 4 {-3,1,3} = 4

The path, {-3, 1, -1 ,7} = 7, will be the maximum sum for the given condition 路径{-3,1,-1,7} = 7,将是给定条件的最大和

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)

Running this on your tree, gives the following output, 在您的树上运行此命令,将得到以下输出,

-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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM