1

Inspired by the answer to the question "Enumerating all paths in a tree", I wrote an adapted version (I don't need the unrooted path):

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

Now, in my "tree" object, I have a number associated with each node: tree.number. I looks like this:

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

I would like to initialize my paths with a 0 value, and sum all tree.numbers of the path, in order to know the sum for each generated path:

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

How should I modify my code to get this result? I'm not seeing how to do it.

Community
  • 1
  • 1
Antonin
  • 1,748
  • 7
  • 19
  • 24
  • 1
    sample data and tree class so we can test / poke at it? – agf Apr 17 '12 at 22:46
  • 3
    `tree is []` is never true as `[]` constructs a new empty list. If `tree` is always a list, check for emptiness with `if not tree:` – Fred Foo Apr 17 '12 at 22:47
  • It's difficult to give you sample data and tree, since then it would be very specific to my question and less relevant for other readers. I'm not sure it's necessary. – Antonin Apr 18 '12 at 07:43

1 Answers1

1

In order to achieve what you want, pass one more argument to the recursion - that would be the sum you have got so far. Also return one more value for each path - its sum:

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

Something like this should work. Please note now you are returning an array of pair of path and integer value. The integer value is the sum along that path.

Hope that helps.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
  • Thanks a lot! Finally, the only problem I have is that the code I wrote here is not generating only paths to leaves (A-B-D, A-C-E, A-C-F, but all paths from the root (A, B, C, A-B and A-C). – Antonin Apr 18 '12 at 08:20
  • I thought about that but then decided you did need it. Just remove the line `rooted_paths = [[[root], value]]` and replace it with `rooted_paths = []` this should do. – Ivaylo Strandjev Apr 18 '12 at 08:21