标签:python algorithm recursion binary-tree tail-recursion
我正在跟随here,我正在尝试将正常的递归函数转换为尾递归函数.我设法理解斐波纳契和阶乘版本,但这个让我很难过.我理解算法在做什么,以及在转换中让我困惑的else语句.
在其他内部,它试图找到一个更接近你正在寻找的数字,然后放弃并找到它找到的数字小于你建议的数字.
我不知道如何编写使尾部递归的辅助函数.对于斐波那契和阶乘,我最终使用了累加器.有没有类似的东西可以在这里使用?
class BSTNode(object):
"""Binary search tree node."""
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __repr__(self):
return '(%s, %r, %r)' % (self.val, self.left, self.right)
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
我知道Python不支持尾递归优化以允许常量堆栈空间但我只是在Python中练习这样做,因为我喜欢语法
解决方法:
而不是做
if right_best is None:
return bst.val
您可以将目前为止找到的最佳结果作为额外参数传递给递归调用,并使递归调用处理此检查.
def find_val_or_next_smallest(bst, x, best=None):
"""
Get the greatest value <= x in a binary search tree.
Returns None if no such value can be found.
"""
if bst is None:
return best
elif bst.val == x:
return x
elif bst.val > x:
return find_val_or_next_smallest(bst.left, x, best)
else:
# bst.val is guaranteed to be the best yet, since if we had
# seen a better value higher up, the recursion would have gone
# the other way from that node
return find_val_or_next_smallest(bst.right, x, bst.val)
标签:python,algorithm,recursion,binary-tree,tail-recursion 来源: https://codeday.me/bug/20190829/1764436.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。