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.

The Idea: Perform a regular binary search, except rather than searching for the element explicitly, continually update the closest difference with the target value.

Complexity: O(logN) time and O(|height|) space

class Solution:
    def closestValue(self, root, target):
        """
        :type root: TreeNode
        :type target: float
        :rtype: int
        """

        min_diff = [sys.maxsize]
        min_val = [root.val]

        def search(root):
            if not root:
                return
            cur_min_diff = abs(root.val - target)
            if cur_min_diff < min_diff[0]:
                min_diff[0] = cur_min_diff
                min_val[0] = root.val

            if target < root.val:
                return search(root.left)
            else:
                return search(root.right)

        search(root)
        return min_val[0]

Python Solution

Same idea, but now iterative.

Last updated

Was this helpful?