Code Logo

BST Find Closest Value

Published at25 Jul 2026
Binary Search Tree Easy 0 views
Like0

Given a sorted array representing a BST's inorder traversal and a target value, find the closest value to the target in the BST. If the array is empty, return -1.

Iterate through the array, tracking the value with the smallest absolute difference to the target. Since the array is sorted, you can also break early once values start moving away.

Example Input & Output

Example 1
Input
[10,20,30,40,50],25
Output
20
Explanation

Closest to 25 is 20

Example 2
Input
[],10
Output
-1
Explanation

Empty

Example 3
Input
[5],5
Output
5
Explanation

Single node match

Example 4
Input
[1,2,3,4,5],3
Output
3
Explanation

3 exists, closest is itself

Example 5
Input
[1,3,5,7],6
Output
5
Explanation

Closest to 6 is 5 or 7, return 5

Algorithm Flow

Recommendation Algorithm Flow for BST Find Closest Value
Recommendation Algorithm Flow for BST Find Closest Value

Solution Approach

function solution(arr, target) {
  if (arr.length === 0) return -1;
  var closest = arr[0];
  for (var i = 1; i < arr.length; i++) {
    if (Math.abs(arr[i] - target) < Math.abs(closest - target)) closest = arr[i];
  }
  return closest;
}

Best Answers

java
class Solution {
    public int solution(int[] nums, int t) {
        if(nums.length==0)return -1;int c=nums[0];
        for(int i=1;i<nums.length;i++){if(Math.abs(nums[i]-t)<Math.abs(c-t))c=nums[i];}
        return c;
    }
}