Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 打印根到叶路径时检测到循环_Python_Algorithm_Graph_Tree_Tree Traversal - Fatal编程技术网

Python 打印根到叶路径时检测到循环

Python 打印根到叶路径时检测到循环,python,algorithm,graph,tree,tree-traversal,Python,Algorithm,Graph,Tree,Tree Traversal,我使用这个问题的解决方案来打印一棵n元树的所有根到叶的路径。 不幸的是,我怀疑,在树的一个分支中有一个循环,因此程序违反了最大递归限制 A / \ B C | /\ D E F | A (back to root) D再次回到A 请告诉我如何处理以下程序中的循环检测 def paths(tree): #Helper function #receives a tree and #returns all p

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

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

例如: A C A C E A、C、F


C被多次访问

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

我尝试使用visted nodes逻辑进行检测,但这并不是很有帮助,因为一个节点可以合法地访问多次:例如:一个C a C E a C F C被访问多次;指向原始项的链接似乎不是正常的枚举a树结果,因为所有路径都应该从根a开始。也许您可以使用一种算法从a查找根,并使用我的循环检测,然后如果没有找到循环,您可以使用alfgorithm查找路径,而不必从a查找路径。