How to get all possible branch with python anytree
You want to have the root path for every leaf node.
Just use the PreOrderIter with a filter_
to retrieve the leaf nodes:
print(list(PreOrderIter(f, filter_=lambda node: node.is_leaf)))
[a, c, e, h]
And then access the path attribute on every node:
print([list(leaf.path) for leaf in PreOrderIter(f, filter_=lambda node: node.is_leaf)])
[[f,b,a], [f,b,d,c], [f,b,d,e], [f,g,i,h]]
If you like to have the path from any node in the tree towards the leaf nodes:
def allpaths(start):
skip = len(start.path) - 1
return [leaf.path[skip:] for leaf in PreOrderIter(start, filter_=lambda node: node.is_leaf)]
print(allpaths(b))
[(b, a), (b, d, c), (b, d, e)]
Please note that there is also a Walker, which serves the path from any node to another one.