AlgoInsight

DSA problem

Closest Binary Search Tree Value

EasyBST / Ordered SetPattern: BST / Ordered Settop600GoogleMicrosoftAmazonSnapchatBloomberg

Given the root of a binary search tree and a target value target (a floating-point number), return the value in the BST that is closest to target. If two values are equally close, return the smaller one.

A brute-force scan of every node and a running minimum-distance check would take O(n) time and ignore the BST structure entirely. Since the tree is ordered, however, you can do much better: each comparison of target against node.val tells you exactly which side of the tree could contain an even closer value.

Specifically, if target < node.val, every value in the right subtree is greater than node.val and therefore farther from target than node.val itself; the only possibly-closer values live in the left subtree. The symmetric argument holds for target > node.val. This means a single root-to-leaf walk suffices.

The optimal solution walks one pointer down the tree, keeping track of the closest value seen so far. Update the candidate whenever |node.val - target| is strictly smaller, with ties broken toward the smaller value to honor the tie-breaking rule. The traversal stops at a null child, giving O(h) time and O(1) space.

Examples

Example 1
Input: root = [4,2,5,1,3], target = 3.714286
Output: 4
Explanation: Walk: 4 (closest=4), 4>target so go left to 2 (|2-3.71|>|4-3.71|, keep 4), 2<target so go right to 3 (|3-3.71|=0.71, closer than 0.28? no — 4 wins). Result is 4.
Example 2
Input: root = [1], target = 4.428571
Output: 1
Explanation: There is only one node, so it is trivially the closest value.
Example 3
Input: root = [2,1,3], target = 2.0
Output: 2
Explanation: The root itself equals the target, so |2 - 2.0| = 0 is the minimum possible distance.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

bstbinary-search-treetreeiterative

Browse all DSA problems