Closest Element in a BST | C++( with comments) | Simple
int minDiff(Node *root, int K)
    {
        //Your code here
        int ans=INT_MAX;
        while(root)
        {
            if(root->data<K)  
            {
                ans=min(ans,K-root->data);
                root=root->right;  //if the root->data is already smaller than K and we have calculated the difference
                                   //then there is no point of going towards left because thaat will decrease 
                                   //the root->data and will increase the difference between root->data and K.
                                   //But we want minimum differnce so we move to right.
            }
            else if(root->data>K)
            {
                ans=min(ans,root->data-K);
                root=root->left;   //if the root->data is already greater than K and we have calculated the difference
                                   //then there is no point of going towards right because that will increase 
                                   //the root->data and will increase the difference between root->data and K.
                                   //But we want minimum differnce so we move to left.
            }
            else  //if root->data==K then simply make difference as 0 and break
            {
                ans=0; 
                break;
            }
        }
        
        return ans;
    }
Comments (0)