Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to traverse a tree in Python?

Assuming I have a list of objects that have the following fields

parent

value

and this defines a tree structure, similar to a directory tree.

I want to traverse the list in a pre-order fashion. What's the most efficient way?

Normally, in other (more imperative) languages I would iterate the values, finding the ones with no parents, then for each, iterating again for every object whose parent is the one I'm currently looking at and so forth, but is there a cleverer way to do this in Python?

like image 965
Bruno Avatar asked Feb 13 '11 21:02

Bruno


People also ask

Which tree traversal is most efficient?

Inorder Traversal. Inorder Traversal is the one the most used variant of DFS(Depth First Search) Traversal of the tree.

What is the most efficient way to traverse a binary search tree?

Try in order traversing of Binary Search tree. The complexity of search is nlogn and traverse is n, which is considered to be the best.

How do you traverse through a tree in python?

Pre-order Traversal In this traversal method, the root node is visited first, then the left subtree and finally the right subtree. In the below python program, we use the Node class to create place holders for the root node as well as the left and right nodes. Then we create a insert function to add data to the tree.


1 Answers

I would first create a more suitable data structure -- capturing the link from a parent to its children:

children = {}
for obj in tree:
    children.setdefault(obj.parent, []).append(obj)

def preorder(root, children):
    yield root.value
    for child in children.get(root, []):
        for value in preorder(child, children):
            yield value

for root in children[None]:
    for value in preorder(root, children):
        print value

You could also use collections.defaultdict here.

like image 157
Sven Marnach Avatar answered Sep 29 '22 18:09

Sven Marnach