Closest Binary Search Tree Value Problem
Description
LeetCode Problem 270.
Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target. If there are multiple answers, print the smallest.
Example 1:

Input: root = [4,2,5,1,3], target = 3.714286
Output: 4
Example 2:
Input: root = [1], target = 4.428571
Output: 1
Constraints:
- The number of nodes in the tree is in the range
[1, 10^4]. 0 <= Node.val <= 10^9-10^9 <= target <= 10^9
Solution
Approach: Walk Down the BST
In a binary search tree we do not need to visit every node. At a node with value v:
- If
target < v, every value in the right subtree is even larger thanv, so it is farther fromtargetthanv. Only the left subtree can do better. - Otherwise, by the same reasoning, only the right subtree can do better.
So we walk a single path from the root, like a search for target, and keep the closest value seen on the way. The closest value in the whole tree is always on this path.
The tie rule needs care: when two values are equally close (for example 3 and 4 for target = 3.5), the problem asks for the smaller one. So we replace the best value when the new distance is smaller, or when it is equal and the new value is smaller.
Complexity: O(h) time, where h is the height of the tree (O(n) when the tree is a chain), and O(1) extra space.
class Solution:
def closestValue(self, root: Optional[TreeNode], target: float) -> int:
best = root.val
node = root
while node:
d, best_d = abs(node.val - target), abs(best - target)
if d < best_d or (d == best_d and node.val < best): # on a tie keep the smaller value
best = node.val
# Values closer to target can only be on target's side of this node.
node = node.left if target < node.val else node.right
return best