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?
I would first create a more suitable data structure — capturing the link from a parent to its children:
You could also use
collections.defaultdicthere.