Approach to creating recursive programs March 29, 1991 Step 1. Identify the function, F, which must be implemented and the data structure. Examples: 1. Determine the location of a data item in an array of size N. 2. Count the number of nodes in a binary tree of size N. 3. Solve a certain puzzle of size N. Note: You are free to determine how "size" is measured. 2. Determine how to implement the function on a very small size data structure. For example, a list or a binary tree of size 0 or a puzzle of size 1. 3. Assume that the function can be implemented on the data structure so long as the size of the data structure does not exceed N-1. 4. Determine a method of implementing the function on a data structure of size N by using solutions for data structures of size N-1 or smaller. EXAMPLES: A. Determine the location of an element in an array of size N. FIND Location of data_item in array, A, of size N If N = 0 Then the data item in not in the array. Else If the data item equals the last (Nth) item in the array Then Location is N Else FIND Location of data_item in array, A, of size N-1. B. Count the number of nodes in a binary tree of size N. COUNT Number_of_Nodes in binary tree, B, of size N. (where N is the number of levels in B) If N = 0 Then Number_of_Nodes = 0 Else COUNT Number_of_NodesL in the left subtree of B (size<=N-1) COUNT Number_of_NodesR in the right subtree of B (size<=N-1) The Number_of_Nodes in B equals the Number_of_Nodes in the left subtree of B plus the Number_of_Nodes in the right subtree of B plus 1 (the root of B). i.e. Number_of_Nodes = Number_of_NodesL + Number_of_NodesR + 1 Note that Number_of_NodesL and Number_of_NodesR are recursive calls to Number_of_Nodes with the left and right subtrees as parameters.