Day 9 Recursion Part I

In programming, recursion means a function definition will include an invocation of the function within its own body.

Call Stacks and Execution Frames:

A recursive approach requires the function invoking itself with different arguments. How does the computer keep track of the various arguments and different function invocations if it’s the same function definition.

Languages make this possible with call stacks and execution contexts

Stacks, a data structure, follow a strict protocol for the order data enters and exits the structure: the last thing to enter is the first thing to leave.

Your programming language often manages the call stack, which exists outside of any specific function. This call stack tracks the ordering of the different function invocations, so the last function to enter the call stack is the first function to exit the call stack.

Below is an example (binary search tree) using recursion.

# Define build_bst() below...
def build_bst(my_list):
  if len(my_list) == 0:
    return 'No Child'
  middle_idx = len(my_list) // 2
  middle_value = my_list[middle_idx]
  print('Middle index: ' + str(middle_idx))
  print('Middle value: ' + str(middle_value))
  tree_node = {'data':middle_value}
  tree_node['left_child'] = build_bst(my_list[:middle_idx])
  tree_node['right_child'] = build_bst(my_list[middle_idx+1:])
  return tree_node
# For testing
sorted_list = [12, 13, 14, 15, 16]
binary_search_tree = build_bst(sorted_list)
print(binary_search_tree)

# fill in the runtime as a string
# 1, logN, N, N*logN, N^2, 2^N, N!
runtime = "???"

 

posted @ 2022-01-18 21:03  M1stF0rest  阅读(31)  评论(0)    收藏  举报