Find Closest Value in BST
Write a function that takes in a BST and a target integer value and returns the closest value to that target in the BST.
def findClosestValueInBst(tree, target):
# Initiate the closest value to infinity
= float("inf")
closestValue = tree
currentNode
while currentNode is not None:
# If the current node's value is closer to the target value then the closesetValue
# then update the closestValue
if abs(currentNode.value - target) < abs(target - closestValue):
= currentNode.value
closestValue
if currentNode.value < target:
= currentNode.right
currentNode
elif currentNode.value > target:
= currentNode.left
currentNode
else:
# Break from the loop if currenNode is equal to the target value
break
return closestValue