http://www.perlmonks.org?node_id=998803

I've historically found writing code for manipulating tree structures awkward; and a primary reason for it is that when things go wrong, visualising why is hampered by the lack of a mechanism for creating convenient, compact and readable dumps of the structures.

Data::Dump, Data::Dumper et al. do a perfectly fine job of dumping the structure in terms of the arrays (or hashes) that hold the tree, but are pretty useless when if comes to visualising the tree structure itself: levels; depth; width; changes from one iteration to the next etc. And I usually find myself resorting to manually manipulating a dump in order to work out what is going on.

For example, a not very complicated, array-based binary tree might get dumped like this:

[ [ [[[[["a", "b"], "c"], ["d", "e"]], [[["f", "g"], "h"], [["i", +"j"], ["k", ["l", "m"]]]]], ["n", [[["o", "p"], "q"], ["r", "s"]]]], ["t", ["u", "v"]] ], [["w", ["x", "y"]], "z"] ]

Try working out how deep; or wide; or which nodes are at the same level; from that. Not to mention seeing what changed between this dump and the previous -- when (for example) re-balancing the tree.

With hand manipulating this you can come up with something like:

Which allows those questions to be answered, but it is hardly concise or convenient; and makes comparing multiple iterations of changes very awkward.

The same tree can be represented this way:

___________/\_________ +___ ________________/\____________ +__/\_ _____________/\______________ /\ / +\ \ ________/\________ ___/\___ / \ / + \ z __/\__ _____/\____ / __/\__ t /\ w + /\ /\ \ /\ __/\__ n /\ \ u v +x y / \ /\ / \ / /\ / \ /\ /\ c d e /\ h /\ / \ /\ q r s a b f g i j k /\ o p l m

which is far nicer.

I've spent the last couple of days trying to code this but haven't yet succeeded. Any offers?

(NOTE: I'm looking for a compact dump to a terminal; not presentation quality graphics here. Ie. I'm not looking for GraphViz or similar, so please don't tell me about those.)


With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

RIP Neil Armstrong