I have a hard time with tree traversal, and so avoid it like the plague... normally.
I have a class that's sort-of (slightly simplified version here, but functionally the same) like:
class Branch(object):
def __init__(self, title, parent=None):
self.title = title
self.parent = parent
I have a dictionary of a bunch of Branch
instances, the titles of each as the keys:
tree = {'Foo Branch': foo, 'Sub-Foo Branch': sub_foo, 'Bar Branch': bar}
Now, I know that there are complex algorithms for making traversal efficient (e.g. MPTT, et al), particularly for use with database-driven projects where efficiency matters the most. I'm not using the database at all, only simple in-memory objects.
Given the title
of a Branch
, I need to get a list
of all descendants of that branch (children, children's children, so-on) from tree
, so:
- Would you still recommended using a complicated (for my algo-less brain :) algorithm like MPTT for efficiency in my case, or is there a simple way to achieve this in a single function?
- If so, which one would you recommend, knowing I'm not using a database?
- Can you provide an example, or is this much larger than I'm thinking?
Note: This isn't a homework assignment. I'm not in school. I'm really just this bad at algorithms. I've used Django MPTT for a project which required DB-stored trees... but still don't understand it very well.