pythonlisttreeanytree

How to get all possible branch with python anytree


I'm using anytree currently to generate my search tree, how do I get all possible branch starting from the root node in list format

from anytree import Node, RenderTree, AsciiStyle

f = Node("f")
b = Node("b", parent=f)
a = Node("a", parent=b)
d = Node("d", parent=b)
c = Node("c", parent=d)
e = Node("e", parent=d)
g = Node("g", parent=f)
i = Node("i", parent=g)
h = Node("h", parent=i)
print(RenderTree(f, style=AsciiStyle()).by_attr())

Current Tree:

f 
|-- b
|   |-- a
|   +-- d
|       |-- c
|       +-- e
+-- g
    +-- i
        +-- h

wanted output (treeBranch):

[[f,b,a], [f,b,d,c], [f,b,d,e], [f,g,i,h]]

I'm not sure if there is a better way of doing this, open to any suggestion.

I want to use this list to check if a new path from user exists in the tree, for example:

newPath = [f, b]

for branch in treeBranch:
    if newPath in branch:
        return true
    else:
        // add new path to tree

Solution

  • 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.