Find the Closest Element in BST | Practice | GeeksforGeeks

Given a BST and an integer. Find the least absolute difference between any node value of the BST and the given integer.
Example 1:
Input:
        10
      /   \
     2    11
   /  \ 
  1    5
      /  \
     3    6
      \
       4
K = 13
Output: 2
Explanation: K=13. The node that has
value nearest to K is 11. so the answer
is 2

Example 2:
Input:
      8
    /   \
   1     9
    \     \
     4    10
    /
   3
K = 9
Output: 0
Explanation: K=9. The node that has
value nearest to K is 9. so the answer
is 0.
Your Task:
You don't need to read input or print anything. Your task is to complete the function minDiff() that takes the root of the BST and an integer K as its input and returns the minimum absolute difference between any node value of the BST and the integer K.
Expected Time Complexity: O(Height of the BST).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 <= Number of nodes <= 100000
0
adarshsharadpandey231 day ago
vector<int> v;
	void inOrder(Node* root)
	{
	    if(root==NULL)
	    {
	        return;
	    }
	    inOrder(root->left);
	    v.push_back(root->data);
	    inOrder(root->right);
	}
    int minDiff(Node *root, int K)
    {
        //Your code here
        int dif=K+1;
        inOrder(root);
        for(int i=0;i<v.size();i++)
        {
            if(v[i]-K>=0 && v[i]-K<dif)
            {
                dif=v[i]-K;
            }
            else if(K-v[i]>=0 && K-v[i]<dif)
            {
                dif=K-v[i];
            }
        }
        return dif;
    
    }
0
rengarajan6 days ago
 def minDiff(self,root, K):
        # code here
        if root is None:
            return float("inf")
        else:
            return min(abs(root.data-K),self.minDiff(root.left,K),self.minDiff(root.right,K))
Python
+1
swastikp17112 weeks ago
Optimized Java Solution ( Iterative approach )
class Solution
{
    static int minDiff(Node  root, int k) 
    { 
        int minAbsDiff=Integer.MAX_VALUE;            
        int absDiff=0;
        
        while(root!=null){

            if(root.data==k) return 0;
            
            absDiff=Math.abs(root.data-k);
            minAbsDiff=Math.min(minAbsDiff,absDiff);
            
            if(k<root.data){
                root=root.left;
            }else{
                root=root.right;
            }
            
        }
        return minAbsDiff;
    } 
}
+1
geniusambi882 weeks ago
Different approach using Ceil and floor function
 
 
 int floor(Node *root ,int x){   int res=0;        while(root!=NULL)    {        if(root->data==x)    {        return root->data;    }        if(root->data>x)        {            root=root->left;        }        else{            res=root->data;            root=root->right;        }    }    return res;}int ceil(Node *root ,int x){   int res=0;        while(root!=NULL)    {        if(root->data==x)    {        return root->data;    }        if(root->data>x)        {            res=root->data;            root=root->left;        }        else{            root=root->right;        }    }    return res;}   int minDiff(Node *root, int K)   {       //Your code here       int f=floor(root,K);       int c= ceil(root,K);       int fd =abs(f-K);       int cd=abs(c-K);       int res =min(fd,cd);       return res;   } 
0
pritamtech19984 weeks ago
nt minDiff(Node *root, int K)   {       if(root){           int d = abs(root->data - K);           if(K > root->data)               return min(d, minDiff(root->right, K));           else if(K < root->data)               return min(d, minDiff(root->left, K));           else               return 0;       }else           return INT_MAX;   }
+1
badgujarsachin831 month ago
	void cheak(Node* root, int k,int &dif){
	    if(root==NULL){
	        return ;
	    }
	    int curdif=abs(k-root->data);
	    if(curdif<dif){
	        dif=curdif;
	    }
	    if(k<root->data){
	        cheak(root->left,k,dif);
	    }
	    else{
	        cheak(root->right,k,dif);
	    }
	    
	}
    int minDiff(Node *root, int K)
    {
     int dif=INT_MAX;
     cheak(root,K,dif);
     return dif;
    }
0
jayanth2642 months ago
 void  finddiff(Node *root, int K,int &diff){    if(root==NULL)    {        return;    }        int currentdiff=abs(K-root->data);    if(currentdiff<diff)    {        diff=currentdiff;    }    if(K<root->data)    {         finddiff(root->left,K,diff);    }    else    {         finddiff(root->right,K,diff);    }    }   int minDiff(Node *root, int K)   {       int diff=INT_MAX;       finddiff(root,K,diff);       return diff;   }
-2
vermabhishek6572 months ago
cpp solution 
 
  int minDiff(Node *root, int K)   {       //Your code here         if(root==NULL)          return K;            queue<Node*> q;            q.push(root);             int res=INT_MAX;             while(q.empty()==false)             {                 Node*curr=q.front();                    if(curr->data==K)                     return 0;                                                 res= min(res,abs(K-curr->data));                                                                        q.pop();                       if(curr->left!=NULL)                       q.push(curr->left);                        if(curr->right!=NULL)                         q.push(curr->right);             }              return res;             }
0
jai20222 months ago
Easy C++ using inorder traversal
 
void inorder(Node* root,int &diff,int K){    if(root==NULL) return;    inorder(root->left,diff,K);    diff = min(diff,abs(K-root->data));    inorder(root->right,diff,K);}   int minDiff(Node *root, int K)   {       //Your code here       int diff = INT_MAX;       inorder(root,diff,K);       return diff;   }
0
emmanueluluabuike2 months ago
Java Solution
static int minDiff(Node root, int k) { 
        // Write your code here
       int ans = 0;
        if(root == null) // base case
            return k;
        if(root.data == k) // base case
            return ans;

        int firstNodeDiff = Math.abs(root.data - k); // sub the first node.data from k to find the min difference
        
        if(k < root.data)
            ans = minDiff(root.left, k);
        else
            ans = minDiff(root.right, k);
        
        return Math.min(ans, firstNodeDiff);
    } 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.