-2

I used the solution to this problem to print all root to leaves path for a n-ary tree I have. Unfortunately, I suspect, there is a cycle in one of the branch of the tree due to which the program breaches the maximum recursion limit.

      A
    /   \
   B     C
   |     /\
   D    E  F
   |
   A (back to root)

D again goes back to A

Please tell me how should I handle the cycle detection in the below program.

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

p.s: I tried using visited nodes logic for detection, but that is not very helpful as a node can be legitimately visited multiple numbers of time:

for Example: A C A C E A C F

C is visited multiple numbers of times

Community
  • 1
  • 1
Bhavish Agarwal
  • 663
  • 7
  • 13

1 Answers1

0

Keep a set on nodes visited and test to make sure the next node to be visited is outside the set of previously visited nodes.

Paddy3118
  • 4,704
  • 27
  • 38
  • I tried using visted nodes logic for detection, but that is not very helpful as a node can be legitimately visited multiple numbers of time: for Example: A C A C E A C F C is visited multiple numbers of times. – Bhavish Agarwal Aug 06 '14 at 07:17
  • Hi @BhavishAgarwal; that link to the original item doesn't seem to be the normal enumerate a tree result as all paths should start at the root A. Maybe you could use an algorithm finding roots from A with my loop detection, then if no loops are found you can use your alfgorithm to find the paths, not necessarilly from A. – Paddy3118 Aug 06 '14 at 13:49