如何在Python中将树作为参数传递给函数

我编写了一个函数,该函数根据我提供的输入在树中找到最接近的数字 但是当我将树参数作为函数传递时,它给我错误的输出

class BST:
  def __init__(self, value):
    self.value=value
    self.left=None
    self.right=None

  def insert(self, value):
    if value < self.value:
      if self.left is None:
        self.left = BST(value)
      else:
        self.left.insert(value)

    else:
      if self.right is None:
        self.right = BST(value)
      else:
        self.right.insert(value)
    return self  


#input
node_value=int(input())
tree_val=list(map(int, input().split()))
for i in range(len(tree_val)):
  tree.insert(tree_val[i])
target=int(input("Enter the value you want to find: ")) 

tree=BST(node_value)

#Main Function
def FindClosestvalueinBST(tree, target):
  return FindClosestvalueinBSTHelper(tree, target, node_value)

def FindClosestvalueinBSTHelper(tree, target, closest):
  if tree is None:
    print("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  


closest=FindClosestvalueinBST(tree, target)
print(closest)

I get the output as Tree is none (as it satisfies the first condition, I can consider her that the tree has not been passed as an argument)

the elements of the tree to be formed are here: 5 15 2 5 13 22 1 4

评论