打印根时检测到循环离开路径

时间:2014-08-06 07:03:19

标签: python algorithm graph tree tree-traversal

我使用this问题的解决方案来打印我所拥有的n-ary树的所有根到叶子的路径。 不幸的是,我怀疑,树的一个分支中有一个循环,因为程序违反了最大递归限制。

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

D再次回到A

请告诉我如何处理以下程序中的循环检测。

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:我尝试使用访问节点逻辑进行检测,但这不是很有用,因为一个节点可以合法访问多个时间段:

例如: 一个C. A C E. A C F

多次访问C

1 个答案:

答案 0 :(得分:0)

在访问过的节点上保留一组并进行测试,以确保要访问的下一个节点位于先前访问过的节点集之外。