Binary Search Tree

find the closest value in BST:

def findClosestValueInBst(tree, target):
    # Write your code here.
    
	if tree is None:
		return tree
	if target==tree.value:
		return target
	
	res=tree.value
	
	while tree:
		if abs(target-res)>abs(tree.value-target):
			res=tree.value
		if target>tree.value:
			tree=tree.right
		else:
			tree=tree.left
	return res		

# This is the class of the input tree. Do not edit.
class BST:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None
-------------------------------------------------------------------
def findClosestValueInBst1(tree, target,data):
    # Write your code here.
    if tree is None:
		return data
	
	if target==tree.value:
		return target
	if abs(target-data)>abs(tree.value-target):
			data=tree.value
	if target>tree.value:
			return findClosestValueInBst1(tree.right, target,data)
	else:
			return findClosestValueInBst1(tree.left, target,data)
	
	return data		

def findClosestValueInBst(tree, target):
    # Write your code here.
    return findClosestValueInBst1(tree,target,tree.value)


# This is the class of the input tree. Do not edit.
class BST:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None
Advertisement