Closest Binary Search Tree Value
Description:
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
Example
Given root = {1}, target = 4.428571, return 1.
Code:
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: the given BST
@param target: the given target
@return: the value in the BST that is closest to the target
"""
def closestValue(self, root, target):
# write your code here
res = root.val
while root:
if abs(root.val-target)<=0.5:
return root.val
if abs(res-target) > abs(root.val-target):
res = root.val
if root.val<target:
root = root.right
else:
root = root.left
return res