Printing Pretty Ascii Trees

I’m terrible at writing recursive algorithms. Absolutely horrible. So for practice I decided to try printing a binary tree where all branches have two children, all in the console. It turns out this is a pretty useful quick-n-dirty debugging tool when creating trees.

I really like formatting of Tree for linux so I decided to steal it.

After 3 straight hours of trying out stupid stuff I finally come to a working solution (my earlier attempts were around 150 lines of code, the solution was like 70):

Which will print cool trees like this one:

I then realized that I could use singly linked lists to represent trees with any number of children, which is totally necessary for the parser I am currently writing. So after 30 minutes I was able to form version 2 for arbitrary trees; this version is surprisingly right around the same length and complexity as the previous version:

And will print trees like this monster:

I also ended up finding a pretty cool implementation by a random stack-overflow user that prints trees in horizontal format (which turns out to be much more limited for the purposes of a console, since it can’t print larger trees, but might look a lot prettier for small trees):

It may be preferable to upgrade to the limited edition Box Drawing characters for best viewing pleasure:

Capture

 

In which case you’ll probably want to use some specific character codes (I used 195, 196 and 192 in the above image).

TwitterRedditFacebookShare

2 thoughts on “Printing Pretty Ascii Trees

  1. Mariano Ruiz

    Thanks for this, I was looking for a simple implementation of a binary tree.

    A lite fix: rand() function won’t generate real random numbers if you don’t initialize it with srand() function first.

    Something like this:

     

    Aside note: to compile the source, if the file is named tree.c, then execute: cc -std=gnu99 -o tree tree.c

     

     

     

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *