Why flatten a tree when you can just traverse it?
Feb 15, 2013 · 1 minute read · CommentsprogrammingRubyrecursion
Michael Feathers wrote a blog post about avoiding explicitly traversing a tree recursively by taking advantage of its representation as nested arrays and using array operations to flatten.
I was unhappy about this solution because
- it creates a bunch of intermediate arrays
- it concatenates arrays repeatedly, which is expensive for a very large tree
- the recursive solution seems more simple, clear, and efficient
So I wrote up the recursive solution. Some features of the solution:
- it uses Ruby’s idiomatic
yield
construct - for convenience, it creates an
Enumerable
so that you can do whatever you want while iterating through the tree
Here’s the code: