This adjusted variant creates the same output but is hopefully
easier to understand and follow than the recursive version.
This version is also not limited by the python stack limit which
is a general good thing to avoid being limited by.
It also adds a bunch of tests to make sure the format is as expected
under various tree structures.
Change-Id: I2ae42c7c1bf72794800929250bcf6ccbe658230b