由于您没有提供任何树/节点类,因此我制作了一个来测试:
class Node:
def __init__(self, data, children=None):
if children is None:
children = []
self.data = data
self.children = children
def __str__(self):
return str(self.data)
__repr__ = __str__
从您的图像中提取的树:
tree = Node("A", [
Node("B", [
Node("E"),
Node("F"),
]),
Node("C"),
Node("D", [
Node("G", [
Node("H"),
Node("I"),
Node("J"),
Node("K"),
])
])
])
您想要的是一种可以获取所有可能的根到叶路径的算法。
def get_all_paths(node, path=None):
paths = []
if path is None:
path = []
path.append(node)
if node.children:
for child in node.children:
paths.extend(get_all_paths(child, path[:]))
else:
paths.append(path)
return paths
测试它会产生您想要的输出:
paths = get_all_paths(tree)
print(paths)
# Prints:
# [[A, B, E], [A, B, F], [A, C], [A, D, G, H], [A, D, G, I], [A, D, G, J], [A, D, G, K]]
但请注意[A,B,E,F]
不是有效路径,因为F
不是以下的孩子E
。所以我认为这是一个错误。