枚举树中的所有路径并操纵与每个节点关联的值

时间:2012-04-17 22:43:42

标签: python algorithm recursion tree

受到answer question "Enumerating all paths in a tree"的启发,我编写了一个改编版本(我不需要无根路径):

def paths(tree):
    #Helper function
    #receives a tree and 
    #returns all paths that have this node as root
    if not tree:
        return []
    else: #tree is a node
        root = tree.ID
        rooted_paths = [[root]]
        for subtree in tree.nextDest:
            useable = paths(subtree)
            for path in useable:
                rooted_paths.append([root]+path)
    return rooted_paths

现在,在我的“树”对象中,我有一个与每个节点关联的数字:tree.number。我看起来像这样:

     A,2
    /   \
  B,5   C,4
   |    /  \
  D,1  E,4 F,3

我想用0值初始化我的路径,并对路径的所有tree.numbers求和,以便知道每条生成路径的总和:

A-B-D: 8
A-C-E: 10
A-C-F: 9

我应该如何修改我的代码才能获得此结果?我没看到怎么做。

1 个答案:

答案 0 :(得分:1)

为了达到你想要的目的,再将一个参数传递给递归 - 这将是你到目前为止的总和。还为每个路径返回一个值 - 它的总和:

def paths(tree, sum_so_far):
    #Helper function
    #receives a tree and 
    #returns all paths that have this node as root
    if not tree:
        return []
    else: #tree is a node
        root = tree.ID
        val = tree.Value
        rooted_paths = [[[root], value]]
        for subtree in tree.nextDest:
            useable = paths(subtree, sum_so_far + val)
            for path in useable:
                rooted_paths.append([[root]+path[0], path[1]])
    return rooted_paths

这样的事情应该有效。请注意,现在返回一对路径和整数值的数组。整数值是沿该路径的总和。

希望有所帮助。