抱歉,如果这是一个普遍的问题,但我是 Python 的初学者,很多时候当我看到其他人使用递归进行编码时,他们为 main 函数创建了一个辅助函数,然后调用该辅助函数,它本身就是递归的。
这似乎与最简单的递归情况有些不同,例如(列表总和,阶乘),其中函数仅调用自身。
有人可以通过示例更仔细地解释这种技术吗?
非常感激。
示例 1:(使用递归反转链表)
def revert_list(self):
self.head = self._revert_helper(self.head)
def _revert_helper(self, node):
temp = None
if node.forward == None:
return node
else:
temp = self._revert_helper(node.forward)
node.forward.forward = node
node.forward = None
return temp
示例 2:(二叉搜索树)
def __contains__(self, key):
return self._bstSearch(self._root, key)
# Returns the value associated with the key.
def valueOf(self, key):
node = self._bstSearch(self._root, key)
assert node is not None, "Invalid may key."
return node.value
# Helper method that recursively searches the tree for a target key:
# returns a reference to the Node. This allows
# us to use the same helper method to implement
# both the contains and valueOf() methods of the Map class.
def _bstSearch(self, subtree, target):
if subtree is None: # base case
return None
elif target < subtree.key: # target is left of the subtree root
return self._bstSearch(subtree.left)
elif target > subtree.key: # target is right of the subtree root
return self.bstSearch(subtree.right)
else: # base case
return subtree