I was reading on converting recursive algorithms to iterative algorithms. I came across a blog-post http://blog.moertel.com/posts/2013-05-11-recursive-to-iterative.html explaining the procedure to convert recursive algorithms first to tail recursive algorithms and then convert tail recursive to iterative one. In the post, it is explained that when we want to convert a recursive algorithm to a tail recursive one, we should first understand what is going on between the return of the recursive call and the return statement of the calling function. Once that is done, we should try to add a secret feature/ accumulator parameters to the recursive function and then decide what to return. I have followed the concept for the examples given in the blog-post but I am not able solve the exercise given at the end of the blog. I am not able to decide what should my accumulator parameter be? How should I make decisions based upon that accumulator parameter. I don't want a solution but some pointers regarding how should I think to solve this problem. Here is the exercise code:
def find_val_or_next_smallest(bst, x):
"""Get the greatest value <= x in a binary search tree.
Returns None if no such value can be found.
"""
if bst is None:
return None
elif bst.val == x:
return x
elif bst.val > x:
return find_val_or_next_smallest(bst.left, x)
else:
right_best = find_val_or_next_smallest(bst.right, x)
if right_best is None:
return bst.val
return right_best
Thanks in advance!