Recursion is a way of coding where a function calls itself in its body. It basically keeps solving smaller instances of the same problem until a final solution is reached. Recursion can be quite complicated and confusing to trace, especially if there are large amounts of information that the code needs to process and so it is extremely easy to make mistakes that lead to massive errors in coding. A good way to approach coding with recursion is to identify the base case scenario(s) that do not require recursion, code this first, and then move on to add in recursive calls. It is useful to keep in mind that if the base is never met in the calls, an infinite loop will occur. Recursion can allow code to do things that it wouldn't be able to do otherwise, but in many cases, it is possible to work without recursion. In these cases, recursion can still be beneficial because it can make the code a lot shorter and easier to read or follow.
I talked about object oriented programming (OOP) and abstract data types (ADTs) in last week's post, and mentioned tracing recursion the week before that. This week, we got to combine these things and work on binary trees. A binary tree is a series of nodes, where each node can have a maximum of 2 children. Expression trees and binary search trees are examples of binary trees. An expression tree is a tree where each internal node is an operation and each leaf is a number, and working through the tree produces a mathematical expression. A binary search tree is a tree where the value of the left child is less than the value of the parent node, and the value of the right child is greater than the value of the parent node. We worked on many functions that could be used on these binary trees, such as functions to add parentheses and create an expression out of an expression tree that can be evaluated, a function to evaluate an expression tree, a function that lists all the nodes with values in between two given values, functions to find the height, longest path, number of leaves etc. At first, I found these really hard to figure out, but as I did more, I realized that as long as I stick to writing down the code for base cases that do not require recursion first, and then work on the recursion code, it wasn't actually all that difficult. Working on these things also helped me become more familiar and comfortable working with ADTs.
No comments:
Post a Comment