Entry no. 5, Week 7:
Topics
1. Summary of Recursion
This weeks topic is on
Recursion.
In general, recursion is an
extremely powerful technique where a function calls itself on a smaller instance of the problem to simplify the initial problem. For coding, recursion is beneficial but has certain drawbacks. Recursion allows us to create algorithms that traverse trees easier. On the other hand, a weakness about recursion is that it takes up lots of memory in stacks and is slower to compute for larger sets of problems.
Let's take a look at some sample code from a lecture exercise
Getting started on coding
evaluate, we must first define a base case. The base case is a case simple enough that it requires no recursion. In this example, when the node is a leaf (ie. no children) it returns the float value inside.
Eg.
if b.left == None and b.right == None: #No children
return b.data
Moving on to the recurse part of
evaluate the recursive case when the node is an interior node (ie. has two children) will be looked at, we can use the built-in python
eval method to evaluate a string that involves arithmetic.
Using this binary tree as an example, we would have to call
evaluate on the left and right children, and append their values as strings to the current data in the interior node ('+') then call
eval on that resulting string.
The body of the function would look something like this.
Eg.
if b.left == None and b.right == None: #No children, base case
return b.data
else: #Has children, recursive case
return eval(str(evaluate(b.left)) + b.data + str(evaluate(b.right)))
Since the recursive and base case both returns a float, the type contract is satisfied. When the method is called on a larger binary tree, it will traverse the tree in such a way that the values from smaller binary trees will be returned and then calculated. Thus since this tree works for smaller cases of binary trees, it will work when called for any binary tree provided that it is not too big for the stacks to handle.
Recursion is an important aspect of computer science because it makes solves problems by breaking them down into sub-problems, like what we did above.