PERENNIAL FASCINATION WITH ALL THINGS TECH

Main menu

Post navigation

Understanding Recursion: Part 3/4

In the previous post, we discussed about how we can deconstruct a programming problem to use recursion to our advantage. We will continue to discuss about programming in this post as well. If you are not prepared to look at code, you may want to skip this post and proceed to the next one in the series. If not, continue reading! Let’s continue to talk about trees then. By now, you understand enough about trees for me to not discuss the basics. If you want a refresher on trees, please read my previous post. In this post, we will look at some common recursive programming problems. You will see the problem and the recursive code to solve it, but not the explanation. We have already discussed how to understand a recursive function in full depth. It’s up to you to understand what’s happening inside these functions here.

Finding the least common ancestor

Given two nodes in a tree, find the node that is the least common ancestor. Here’s the recursive method to do it:

Up until now, we looked at recursion from the programmer’s perspective. In the next post, we will discuss about how the machine sees this whole thing. We will see what it does once we make the recursive call.