【发布时间】:2021-01-28 05:10:07
【问题描述】:
我的代码在下面创建一个二叉搜索树,然后使用递归方法返回最接近的值。当我在调试模式下运行它时,我可以看到它在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, target, closestValue)
def closest_helper(self, currentNode, target, 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, target, closestValue)
elif target > currentNode.value:
return self.closest_helper(currentNode.right, target, 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))
【问题讨论】:
-
也许
returninfindClosestValueInBST... -
这行得通。谢谢
标签: python-3.x algorithm recursion data-structures binary-search-tree