Recursion in a binary tree…

Cosmocoder
2 min readFeb 11, 2022

…the flowchart (JavaScript)

Out of all data structures, few are as exciting to me as the binary tree.

Something this simple, intuitive and utilitarian is easy to admire. And when you combine it with recursion as a means of traversal, it gets even better.

The function -

When I first came across the approach above, I couldn’t believe its simplicity, but I also couldn’t (easily) mentally track the flow of it.

Recursion is another one of my favorite topics and so now, using this snippet, I decided to finally diagram every execution context for the traversal of the left subtree.

each node is instantiated using the following-

The diagram begins with the root node (5) being passed in and, when complete, will have logged 1, 2, 3, 5, 7, 8 and 9 to the console

Being somewhat of a visual learner myself, it’s helped me greatly to write out each execution context in order to fully grasp what is happening in a recursive function…

Admittedly it’s a laborious perusal but for me it helped to visualize the order of execution in the code block. Perhaps anyone who has tried to console.log their way into understanding recursion might enjoy seeing it laid out graphically.

--

--

Cosmocoder

Hi. I’m Nathan and I’m a full-stack software dev making my way through DS and Algo. Looking forward to sharing experiences along the way.