Why flatten a tree when you can just traverse it?
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
yieldconstruct - for convenience, it creates an
Enumerableso that you can do whatever you want while iterating through the tree
Here’s the code:
{{% gist 4963218 %}}