您好,我想知道是否有办法在不改变变量值的情况下递归函数。
这是我的代码:
def helper_list_range(self, low, high, rangelist):
if self is EmptyValue:
return rangelist
else:
if self.left is not None and self.right is not None:
if self.root <= high and self.root >= low:
rangelist.append(self.root)
self.left.helper_list_range(rangelist)
self.right.helper_list_range(rangelist)
return rangelist
def list_range(self, low, high):
rangelist = []
self.helper_list_range(low, high, rangelist)
return rangelist
正如您所看到的那样,我正在使用辅助函数,以便在函数执行递归时附加到 rangelist 而不更改其值。
我想知道有没有办法可以在不使用辅助函数的情况下完成此操作。使用辅助函数似乎有点模糊。
答案 0 :(得分:2)
我认为你寻找默认参数:
def list_range(self, low, high, rangelist = None):
if rangelist is None:
rangelist = []
# here goes the code of helper_list_range
答案 1 :(得分:1)
如果我是你,我不会将自我作为参数。传递树的根值然后再进行处理会更好。我也不会继续传递列表,然后将值附加到它。我认为通过堆叠的返回调用建立列表值更有意义。
根据您对BST的定义,我使用一个函数为您的问题编写了一个简短的解决方案。我还没有测试过,因为我没有你的数据结构,所以如果有任何错误请告诉我。
def list_range(node, low, high):
# base case values for each side of the tree
lowerHalf = []
upperHalf = []
# You have to check each node separately since one could be not None
# You also have to check that the subtree can even satisfy your value
if node.left != None and node.root >= low:
lowerHalf = list_range(node.left, low, high)
if node.right != None and node.root <= high:
upperHalf = list_range(node.right, low, high)
# if the root value is in the range then we just stick it in the middle of both return values
if low <= node.root <= high:
return lowerHalf + node.root + upperHalf
# otherwise we keep stepping down
else:
return lowerHalf + upperHalf