Sunday, 15 March 2015

Recursion with multiple conditions.

So far if you've been reading my blog, i've discussed about recursion with one base case and one else statement that has recursive part. But lets discuss next level of recursion.

Multiple conditions for recursion:

  • Sometimes when writing a function you may come across a situation where you have to use recursion on a specific value on a specific condition, but if case 1 doesn't pass the condition then you may have to use recursion for another value.
  • take an example of this binary search tree:

  • As you can see above, 8 is the root and everything on the left of the root is smaller than 8, and everything on the right is larger. making it a Binary Search Tree (BST). 
  • BST allows for quicker search for a specific object/value anywhere in the tree. because of left being smaller and right being bigger. (much line binary search algorithm) 
Example of multiple condition recursion in BST:
  • In BST, suppose you're implementing this function:

  • this function goes through a BST tree and returns a list of nodes which are in between the start and end value.
  • in order to write the body we must first draw a diagram, in this case:
  • lets think about the base case. in this function if there is no node, then return an empty list, thus return [] if node is None else.....
  • now consider the example list_between(b, 3, 11), where it has to visit both left and right side of each node. 
  • this requires multiple if statements inside the else.
  • now lets the start value, which is 3, and look at the definition of the BST. (everything of the left is smaller than the root and everything on the right is larger). this makes our code much much simpler.
  • 3 < 8, which means if the root node is larger than start value, visit left using recursion to find values. 
  • and the end value which is 11, 11 > 8, meaning if the root node is smaller than end value, visit right using recursion. 
  • no what if the root Node is start <= node <= end? We must return that value because it is in between both start and end (or it equals start and end). 
  • therefore the we no have multiple conditions for recursion.
  • and now we can concatenate and return a list with the nodes in b/w the start and end.
Having multiple conditions for recursion makes writing the code much harder, but if diagrams are used it makes the writing the code way more easier!

No comments:

Post a Comment