问题描述
下面的代码创建了一个二叉搜索树,然后使用递归方法返回最接近的值。当我在调试模式下运行此命令时,我可以看到它在closestValue
中存储了正确的值,但是终端会显示None
。
我需要编辑什么代码行才能返回正确的值?
class Node:
def __init__(self,value,left=None,right=None):
self.value = value
self.left = left
self.right = right
class BST:
def __init__(self):
self.head = None
def insert(self,value):
n = Node(value)
if self.head == None:
self.head = n
return
else:
parent = self.head
while parent != None:
if parent.value < n.value:
if parent.right == None:
parent.right = n
break
else:
parent = parent.right
elif parent.value > n.value:
if parent.left == None:
parent.left = n
break
else:
parent = parent.left
else:
pass
def findClosestValueInBST(self,target,closestValue):
currentNode = self.head
self.closest_helper(currentNode,closestValue)
def closest_helper(self,currentNode,closestValue):
if currentNode == None:
return closestValue
if abs(target - closestValue) > abs(target - currentNode.value):
closestValue = currentNode.value
if target < currentNode.value:
return self.closest_helper(currentNode.left,closestValue)
elif target > currentNode.value:
return self.closest_helper(currentNode.right,closestValue)
else:
return closestValue
array = [10,5,15,2,7,13,22]
bst = BST()
for num in array:
bst.insert(num)
print(bst.findClosestValueInBST(23,100))
解决方法
只需在函数中添加return。由于您还没有退货,因此终端会显示None
def findClosestValueInBST(self,target,closestValue):
currentNode = self.head
return self.closest_helper(currentNode,closestValue)