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

Try It Yourself
redirect icon

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.

C++
#include <iostream>
#include <vector>
#include <climits>
using namespace std;

// Structure of a tree node
struct Node {
    int data;
    Node* left;
    Node* right;
    Node(int val) {
        data = val;
        left = right = nullptr;
    }
};


// Function to find least absolute difference
int minDiff(Node* root, int k) {
    if (root == nullptr) return INT_MAX;
    
    // Diff with root
    int diff = abs(root->data - k);

    // Return the minimum of three values: root
    // minimum in left and right subtrees
    return min(diff, min(minDiff(root->left, k), 
                         minDiff(root->right, k)));
}

int main() {
    Node* root = new Node(10);
    root->left = new Node(5);
    root->right = new Node(15);
    root->left->left = new Node(2);
    root->left->right = new Node(7);
    root->right->left = new Node(12);
    root->right->right = new Node(20);

    int k = 9;
    cout << minDiff(root, k);
    return 0;
}
Java
import java.util.*;

// Structure of a tree node
class Node {
    int data;
    Node left, right;
    Node(int val) {
        data = val;
        left = right = null;
    }
}

public class Main {
    
    // Function to find least absolute difference
    static int minDiff(Node root, int k) {
        if (root == null) return Integer.MAX_VALUE;
        
        // Diff with root
        int diff = Math.abs(root.data - k);
        
        // Return the minimum of three values: root
        // minimum in left and right subtrees
        return Math.min(diff, Math.min(minDiff(root.left, k), 
                                      minDiff(root.right, k)));
    }

    public static void main(String[] args) {
        Node root = new Node(10);
        root.left = new Node(5);
        root.right = new Node(15);
        root.left.left = new Node(2);
        root.left.right = new Node(7);
        root.right.left = new Node(12);
        root.right.right = new Node(20);

        int k = 9;
        System.out.println(minDiff(root, k));
    }
}
Python
# Structure of a tree node
class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None

# Function to find least absolute difference
def minDiff(root, k):
    if root is None: return float('inf')
    
    # Diff with root
    diff = abs(root.data - k)
    
    # Return the minimum of three values: root
    # minimum in left and right subtrees
    return min(diff, min(minDiff(root.left, k), 
                         minDiff(root.right, k)))

if __name__ == '__main__':
    root = Node(10)
    root.left = Node(5)
    root.right = Node(15)
    root.left.left = Node(2)
    root.left.right = Node(7)
    root.right.left = Node(12)
    root.right.right = Node(20)

    k = 9
    print(minDiff(root, k))
C#
using System;

// Structure of a tree node
public class Node {
    public int data;
    public Node left, right;
    public Node(int val) {
        data = val;
        left = right = null;
    }
}

public class Program {
    
    // Function to find least absolute difference
    static int minDiff(Node root, int k) {
        if (root == null) return int.MaxValue;
        
        // Diff with root
        int diff = Math.Abs(root.data - k);
        
        // Return the minimum of three values: root
        // minimum in left and right subtrees
        return Math.Min(diff, Math.Min(minDiff(root.left, k), 
                                      minDiff(root.right, k)));
    }

    public static void Main() {
        Node root = new Node(10);
        root.left = new Node(5);
        root.right = new Node(15);
        root.left.left = new Node(2);
        root.left.right = new Node(7);
        root.right.left = new Node(12);
        root.right.right = new Node(20);

        int k = 9;
        Console.WriteLine(minDiff(root, k));
    }
}
JavaScript
// Structure of a tree node
function Node(val) {
    this.data = val;
    this.left = null;
    this.right = null;
}

// Function to find least absolute difference
function minDiff(root, k) {
    if (root === null) return Number.MAX_VALUE;
    
    // Diff with root
    let diff = Math.abs(root.data - k);
    
    // Return the minimum of three values: root
    // minimum in left and right subtrees
    return Math.min(diff, Math.min(minDiff(root.left, k), 
                                   minDiff(root.right, k)));
}

let root = new Node(10);
root.left = new Node(5);
root.right = new Node(15);
root.left.left = new Node(2);
root.left.right = new Node(7);
root.right.left = new Node(12);
root.right.right = new Node(20);

let k = 9;
console.log(minDiff(root, 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.
C++
#include <iostream>
using namespace std;

class Node
{
  public:
    int data;
    Node *left;
    Node *right;

    Node(int x)
    {
        data = x;
        left = right = nullptr;
    }
};

// Find minimum absolute difference with k
int minDiff(Node *root, int k)
{
    int res = INT_MAX;
    Node *current = root;

    while (current != nullptr) {
        
        // Update answer
        res = min(res, abs(current->data - k));

        // Move according to BST property
        if (current->data > k) {
            current = current->left;
        } else {
            current = current->right;
        }
    }

    return res;
}

// Driver Code
int main()
{
    Node *root = new Node(9);
    root->left = new Node(4);
    root->right = new Node(17);
    root->left->left = new Node(3);
    root->left->right = new Node(6);
    root->left->right->left = new Node(5);
    root->left->right->right = new Node(7);
    root->right->right = new Node(22);
    root->right->right->left = new Node(20);

    int k = 18;

    cout << minDiff(root, k);

    return 0;
}
Java
import java.util.Arrays;

class Node {
    public int data;
    public Node left;
    public Node right;

    public Node(int x) {
        data = x;
        left = right = null;
    }
}

public class Main {
    // Find minimum absolute difference with k
    static int minDiff(Node root, int k) {
        int res = Integer.MAX_VALUE;
        Node current = root;

        while (current!= null) {
            
            // Update answer
            res = Math.min(res, Math.abs(current.data - k));
            
            // Move according to BST property
            if (current.data > k) {
                current = current.left;
            } else {
                current = current.right;
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Node root = new Node(9);
        root.left = new Node(4);
        root.right = new Node(17);
        root.left.left = new Node(3);
        root.left.right = new Node(6);
        root.left.right.left = new Node(5);
        root.left.right.right = new Node(7);
        root.right.right = new Node(22);
        root.right.right.left = new Node(20);

        int k = 18;
        System.out.println(minDiff(root, k));
    }
}
Python
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Find minimum absolute difference with k
def minDiff(root, k):
    res = float('inf')
    current = root

    while current is not None:
        
        # Update answer
        res = min(res, abs(current.data - k))
        
        # Move according to BST property
        if current.data > k:
            current = current.left
        else:
            current = current.right

    return res

# Driver Code
root = Node(9)
root.left = Node(4)
root.right = Node(17)
root.left.left = Node(3)
root.left.right = Node(6)
root.left.right.left = Node(5)
root.left.right.right = Node(7)
root.right.right = Node(22)
root.right.right.left = Node(20)

k = 18
print(minDiff(root, k))
C#
using System;

public class Node
{
    public int data;
    public Node left;
    public Node right;

    public Node(int x)
    {
        data = x;
        left = right = null;
    }
}

class Program
{
    // Find minimum absolute difference with k
    static int minDiff(Node root, int k)
    {
        int res = int.MaxValue;
        Node current = root;

        while (current!= null)
        {
            // Update answer
            res = Math.Min(res, Math.Abs(current.data - k));
           
            // Move according to BST property
            if (current.data > k)
            {
                current = current.left;
            }
            else
            {
                current = current.right;
            }
        }

        return res;
    }

    static void Main(string[] args)
    {
        Node root = new Node(9);
        root.left = new Node(4);
        root.right = new Node(17);
        root.left.left = new Node(3);
        root.left.right = new Node(6);
        root.left.right.left = new Node(5);
        root.left.right.right = new Node(7);
        root.right.right = new Node(22);
        root.right.right.left = new Node(20);

        int k = 18;
        Console.WriteLine(minDiff(root, k));
    }
}
JavaScript
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Find minimum absolute difference with k
function minDiff(root, k) {
    let res = Number.MAX_SAFE_INTEGER;
    let current = root;

    while (current!== null) {
    
        // Update answer
        res = Math.min(res, Math.abs(current.data - k));
    
        // Move according to BST property
        if (current.data > k) {
            current = current.left;
        } else {
            current = current.right;
        }
    }

    return res;
}

// Driver Code
let root = new Node(9);
root.left = new Node(4);
root.right = new Node(17);
root.left.left = new Node(3);
root.left.right = new Node(6);
root.left.right.left = new Node(5);
root.left.right.right = new Node(7);
root.right.right = new Node(22);
root.right.right.left = new Node(20);

let k = 18;
console.log(minDiff(root, k));

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