[英]Find Closest Value In BST
为什么我得到一个错误,缺少 1 个必需的位置参数 root = findClosestValueInBst(8,)
类型错误:findClosestValueInBst() 缺少 1 个必需的位置参数:“目标”
def findClosestValueInBst (tree, target):
return findClosestValueInBstHelper(tree, target, float('inf'))
def findClosestValueInBstHelper(tree, target, closest):
if tree is None:
return closest
if abs(target-closest) > abs(target - tree.value):
closest = tree.value
if target < tree.value:
return findClosestValueInBstHelper(tree.left, target, closest)
elif target > tree.value:
return findClosestValueInBstHelper(tree.right, target, closest)
else:
return closest
root = findClosestValueInBst(8,)
root.left = findClosestValueInBst(5)
root.right = findClosestValueInBst(14)
root.left.left = findClosestValueInBst(4)
root.left.right = findClosestValueInBst(6)
root.left.right.left = findClosestValueInBst(8)
root.left.right.right = findClosestValueInBst(7)
root.right.right = findClosestValueInBst(24)
root.right.right.left = findClosestValueInBst(22)
result = findClosestValueInBstHelper(root, 3)
print(result)
您定义了一个 function,它需要两个 arguments:
def findClosestValueInBst(树,目标)
稍后您尝试仅使用一个参数调用它:
root = findClosestValueInBst(8,)
您看到的错误:
类型错误:findClosestValueInBst() 缺少 1 个必需的位置参数:“目标”
告诉您它正在尝试调用 function,但它不能,因为它不知道将名为“target”的参数设置为什么,因为您只传递了一个参数。
我已经浏览了您的代码,看来您首先需要通过添加节点来创建 BST。 这可以通过以下步骤完成 -
TreeNode
class ,它具有三个参数 - value
、 left
节点和right
节点。这段代码应该给你一个想法 -
class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def findClosestValueInBST(tree, target):
return findClosestValueInBstHelper(tree, target, tree.value)
def findClosestValueInBstHelper(tree, target, closest):
# Base condition
if tree is None:
return closest
if abs(target - closest) > abs(target - tree.value):
closest = tree.value
# If the target is present in the left subtree
if target < tree.value:
return findClosestValueInBstHelper(tree.left, target, closest)
# If the target is present in the right subtree
elif target > tree.value:
return findClosestValueInBstHelper(tree.right, target, closest)
else:
return closest
# Here we are creating the BST
root = TreeNode(8)
root.left = TreeNode(5)
root.right = TreeNode(14)
root.left.left = TreeNode(4)
root.left.right = TreeNode(6)
root.left.right.left = TreeNode(8)
root.left.right.right = TreeNode(7)
root.right.right = TreeNode(24)
root.right.right.left = TreeNode(22)
closestValue = findClosestValueInBST(root, 3)
print("The closest value is: " + str(closestValue))
closestValue = findClosestValueInBST(root, 19)
print("The closest value is: " + str(closestValue))
我希望这有帮助。 快乐编码:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.