I'm writing a breadth depth-first tree traversal function, and what I want to do is this:
def traverse(node):
yield node
for n in node.children:
yield_all traverse(n) # << if Python had a yield_all statement
The idea is to end up with a (flat) sequence of nodes in the tree.
Approach #1: (propagating yields)
def traverse(node):
yield node
for n in node.children:
for m in traverse(n):
yield m
Approach #2: (flattening sequences)
def traverse(node):
return itertools.chain([node],*(traverse(n) for n in node.children))
The first approach seems more clean, but I feel weird explicitly yield
ing each node in the subtree at each level.
The second approach is terse and slightly dirty, but it matches what I would write in Haskell:
traverse node = node : concatMap traverse (children node)
So my question is: Which is better? Or am I missing a best 3rd option?