VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-closest-element-binary-search-tree/

⇱ Minimum diff with a given value in BST - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum diff with a given value in BST

Last Updated : 17 May, 2026

Given a binary search tree and a value k. we need to find the least absolute difference between any node value of the BST and the given k.  

Examples:

Input :  

👁 bst1

k = 7
Output:  1
Explanation: The closest value to 7 is 6, hence the minimum difference is 1.


Input :

👁 1

k = 18
Output:  1

Complete Traversal - O(n) Time and O(h) Space

The idea is to do Inorder traversal of given binary search tree in an auxiliary array and then by taking absolute difference of each element find the node having minimum absolute difference with given target value K.


Output
1

Using BST Property - O(h) Time and O(1) Space

The idea is to traverse the BST starting from the root and keep track of the closest value to k found so far. At each node, if the current value is closer to k, we update our closest. Depending on whether k is smaller or larger than the current node’s value, we move to the left or right subtree.

Step by Step implementation:

  • Start with the root node and initialize a variable to store the closest value.
  • Traverse the BST while the current node is not null.
  • Update the closest value if the current node’s value is closer to k.
  • Move to the left subtree if k is smaller, otherwise move to the right subtree.
  • Return the closest value after traversal completes.

Output
1

Time Complexity: O(h), where h is the height of the BST, as we traverse only one path.
Space Complexity: O(1), for the iterative approach, as no extra space is used.

Comment