Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerating all paths in a tree

I was wondering how to best implement a tree data structure to be able to enumerate paths of all levels. Let me explain it with the following example:

     A
   /   \
   B    C
   |    /\
   D   E  F

I want to be able to generate the following:

A
B
C
D
E
F
A-B
A-C
B-D
C-E
C-F
A-B-D
A-C-E
A-C-F

As of now, I am executing a depth-first-search for different depths on a data structure built using a dictionary and recording unique nodes that are seen but I was wondering if there is a better way to do this kind of a traversal. Any suggestions?

like image 224
Legend Avatar asked Apr 15 '11 01:04

Legend


1 Answers

Whenever you find a problem on trees, just use recursion :D

def paths(tree):
  #Helper function
  #receives a tree and 
  #returns all paths that have this node as root and all other paths

  if tree is the empty tree:
    return ([], [])
  else: #tree is a node
    root = tree.value
    rooted_paths = [[root]]
    unrooted_paths = []
    for subtree in tree.children:
        (useable, unueseable) = paths(subtree)
        for path in useable:
            unrooted_paths.append(path)
            rooted_paths.append([root]+path)
        for path in unuseable:
            unrooted_paths.append(path)
    return (rooted_paths, unrooted_paths)

def the_function_you_use_in_the_end(tree):
   a,b = paths(tree)
   return a+b
like image 155
hugomg Avatar answered Oct 02 '22 14:10

hugomg