270. Closest Binary Search Tree Value

Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.

Note:

  • Given target value is a floating point.
  • You are guaranteed to have only one unique value in the BST that is closest to the target.

Solution:

class Solution(object):
    def closestValue(self, root, target):
        """
        :type root: TreeNode
        :type target: float
        :rtype: int
        """
        if not root:
            return float('inf')
        child = root.left if target < root.val else root.right
        val = self.closestValue(child, target)
        return min(root.val, val, key=lambda x: abs(x - target))

results matching ""

    No results matching ""