[email protected]: ~/site/blog

Visualizing Binary Tree

3 min. read 5 August 2022

The Story

Hello people! This is my first article on my personal blog, I've waited for so long before writing something. Usually, I don't have things to say but, I hope this experience may help someone.

Many developers, when debugging programs, place some random print statement (instead of using a debugging tool such as gdb, lldb, but, anyway...). This simplistic approach (or the serious one) does not help in visualizing graph-like data structures, like Binary Search Tree!
I had to debug my implementation of Binary Search Tree (using C++ vectors with indices, instead of pointers) for the Contest and Competitive Programming course at my university. Thus, I asked myself: "Mhh, I remember that exist a tool to visualize tree better", I was no wrong! But, what was the name? Urgh...

Lost to myself, a thought cross my mind, where I saw that tool? I remember I was watching a video on YouTube, about Control Flow Graphs during compilation phases.

That's it!

The tool was Graphviz!

Graphviz is open source graph visualization software. Graph visualization is a way of representing structural information as diagrams of abstract graphs and networks. It has important applications in networking, bioinformatics, software engineering, database and web design, machine learning, and in visual interfaces for other technical domains.

- The Graphviz Authors (https://www.graphviz.org)

Winnie Pooh thinking
Me trying to remember the tool's name

The Code

So, I read the documentation and went straight on to my code. I implemented a BFS traversal into my BST and generated Graphviz code.

I think the code is explained by itself. It is a classic BFS and the Graphviz code is emitted using std::stringstream. Let's try the code with a simple BST.

And, here it is the output:

Now, putting the code in a Graphviz editor we obtain the following image.


I hope this wall of text (and code) can help someone to visualize a graph-based data structure to understand what is going on.

P.S. I discovered that Eli Bendersky already did an article about this stuff, I leave the link here (take a look!).

visualizing-binary-tree.html (END)