Sunday, 2 March 2014

Recursion

When I was introduced to recursion, my first thought thought it was quite messy and challenging to grasp the concept. In order to try to understand recursion, I not only browsed several examples of recursive code, but I also attempted to make analogies of recursion in real life. For example, I imagined it as when you would put two mirrors facing each other and producing infinite reflections, but then I realized that that would be an infinite loop. That lead me to the realization that it needs to stop at one point and got me thinking about base cases. Only then did I start to understand and appreciate the beauty of beauty and came to an understanding that in order to understand recursion, you have to understand recursion.

The fundamental concept for recursive methods is surprisingly simple: A function that calls itself. Now you might ask how will it ever stop if it keeps calling itself? Well that is where selection statements come in and set a base case. Recursion is an extremely useful and powerful tool that is able to replace many complex mathematical algorithms or can easily navigate through trees which is a hierarchical  system of nodes and leaves. The node at the top of the system called the root, branches into other nodes which also branch into other nodes until it reaches a leaf which is a node with no children. With recursion, you can navigate through the whole tree, no matter how large with the same recursive code. You may also manipulate the way you traverse the tree such as Post-Order traversal which visits the node then the left branch followed by the right, In-Order traversal which visits the left, followed by the node, then the right, or Post-Order traversal which goes to the left, then the right, and then finally the node.

Recursion has expanded my coding prowess exponentially and will shorten my code, as well as allow me to think at a more advanced level.