簡體   English   中英

在 BST 中查找最接近的值

[英]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。 這可以通過以下步驟完成 -

  1. 首先創建一個TreeNode class ,它具有三個參數 - valueleft節點和right節點。
  2. 然后在您的助手 function 中,您需要檢查在哪個子樹中存在最接近的值,即在左子樹或右子樹中。

這段代碼應該給你一個想法 -

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM