270. Closest Binary Search Tree Value

Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target.

Example 1:

Input: root = [4,2,5,1,3], target = 3.714286 Output: 4

  • code
class Solution:
    def closestValue(self, root: Optional[TreeNode], target: float) -> int:
        mindif = inf
        res = root.val
        while root:
            curdif = abs(root.val - target)
            if curdif < mindif:
                mindif = curdif
                res = root.val
            if root.val >= target:
                root = root.left
            else:
                root = root.right
        
        return res