During A2, I have used recursion in every function. It could simplify function call for itself. For example, in binary search tree, we can apply recursive during our search so that searching recursively go through from left to right in order to find the specific value in shorter time.
def list_internal_between(node, start, end):
''' (BTNode, object, object) ->
Return a Python list of the data from all internal nodes of
the tree rooted at node that are between start and end,
inclusive.
>>> list_internal_between(None, 3, 13)
[]
>>> b = BTNode(8)
>>> b = insert(b, 4)
>>> b = insert(b, 2)
>>> b = insert(b, 6)
>>> b = insert(b, 12)
>>> b = insert(b, 14)
>>> b = insert(b, 10)
>>> L = list_internal_between(b, 3, 13)
>>> L.sort()
>>> L
[4, 8, 12]
'''
if node is None:
return []
else:
left_list = (list_internal_between(node.left, start, end)
if node.data > start
else [])
right_list = (list_internal_between(node.right, start, end)
if node.data < end
else [])
node_list = ([node.data]
if (start <= node.data <= end and not is_leaf(node))
else [])
return left_list + node_list + right_list
For this function call, recursive function check children of the tree from left side to right side in post order. When we do the recursion, firstly, we break down the question into small pieces, then put them together or use them later.
No comments:
Post a Comment