【发布时间】:2017-11-07 15:33:32
【问题描述】:
我正在阅读有关将递归算法转换为迭代算法的内容。我遇到了一篇博客文章http://blog.moertel.com/posts/2013-05-11-recursive-to-iterative.html,解释了首先将递归算法转换为尾递归算法,然后将尾递归转换为迭代算法的过程。在帖子中,解释了当我们要将递归算法转换为尾递归算法时,我们应该首先了解return of the recursive call和return statement of the calling function.之间发生了什么,一旦完成,我们应该尝试添加递归函数的秘密特征/累加器参数,然后决定返回什么。我遵循了博客文章中给出的示例的概念,但我无法解决博客末尾给出的练习。我无法决定我的累加器参数应该是什么?我应该如何根据该累加器参数做出决定。我不想要一个解决方案,而是一些关于我应该如何解决这个问题的指示。下面是练习代码:
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
提前致谢!
【问题讨论】:
-
@VPfB 谢谢。我会尽力让你知道。
-
如果我无法通过,我会请求解决方案。
-
是的。我正在尝试存储 nextSmallValue 并将其传递给连续的尾递归调用。但我仍然在某些情况下陷入困境。
-
您的代码不在尾递归中,因为尾递归表明您在递归调用后没有代码。
-
是的。我想将该代码转换为尾递归。
标签: python algorithm recursion