1. Introduction

A Binary Search Tree (BST) is a special type of binary tree in which each node follows a specific ordering rule.

In this problem, we are given:

  • The root node of a Binary Search Tree.
  • An integer k.

Our task is to find the minimum absolute difference between k and the value of any node in the BST.

In simple words, we need to find the node whose value is closest to the given integer k.

Example:

Code
Input:
root = [10, 2, 11, 1, 5, N, N, N, N, 3, 6, N, 4]
k = 13

Output:
2

Explanation:

The closest node value to 13 is 11.

Code
|11 - 13| = 2

Therefore, the answer is 2.

2. Understanding the Binary Search Tree

Before solving the problem, we should understand the BST property.

A Binary Search Tree follows three important rules:

  1. All values in the left subtree are smaller than the root.
  2. All values in the right subtree are greater than the root.
  3. Both left and right subtrees must also follow BST rules.

Example:

Code
          10
         /  \
        5    15
       / \   / \
      2   7 12  20

If we want to search for the value 12:

  • Start from 10.
  • Since 12 is greater than 10, move right.
  • Reach 15.
  • Since 12 is smaller than 15, move left.
  • Reach 12.

We can use the same searching logic to solve the Closest in BST problem.

3. Approach – Using BST Property

Instead of visiting every node, we can use the BST property to eliminate unnecessary searches.

Algorithm:

  1. Initialize minDifference with int.MaxValue.
  2. Start traversing from the root.
  3. Calculate the absolute difference between the current node value and k.
  4. Compare the current difference with minDifference.
  5. Update minDifference if the current difference is smaller.
  6. If the difference is zero, return zero immediately.
  7. If k is smaller than the current node value, move to the left child.
  8. Otherwise, move to the right child.
  9. Continue until the current node becomes null.
  10. Return the minimum difference.

4. C# Implementation

C#
class Solution {
    public int minDiff(Node root, int k) {

        int minDifference = int.MaxValue;

        while (root != null) {

            int diff = Math.Abs(root.data - k);

            minDifference = Math.Min(minDifference, diff);

            // Exact match found
            if (diff == 0) {
                return 0;
            }

            // Search in the left subtree
            if (k < root.data) {
                root = root.left;
            }

            // Search in the right subtree
            else {
                root = root.right;
            }
        }

        return minDifference;
    }
}

5. Explaining the Code Line by Line

Step 1: Initialize minimum difference

C#
int minDifference = int.MaxValue;

We initialize the minimum difference with the maximum possible integer value.

Why?

Because we need to compare every visited node's difference and find the smallest one.

Step 2: Traverse the BST

C#
while (root != null)

We continue traversing until there are no more nodes to visit in the selected search path.

Step 3: Calculate absolute difference

C#
int diff = Math.Abs(root.data - k);

Math.Abs() returns the positive difference between two numbers.

Example:

C#
root.data = 10;
k = 13;

diff = Math.Abs(10 - 13);

// Result: 3

Step 4: Update the minimum difference

C#
minDifference = Math.Min(minDifference, diff);

Math.Min() returns the smaller of the two values.

For example:

Code
Current minimum = 3
New difference  = 2

Updated minimum = 2

Step 5: Check for an exact match

C#
if (diff == 0) {
    return 0;
}

If the current node value is equal to k, the difference is zero.

Zero is the smallest possible absolute difference, so we can return immediately.

Step 6: Move towards the left subtree

C#
if (k < root.data) {
    root = root.left;
}

If k is smaller than the current node value, the closest possible value must be searched for in the left subtree.

Step 7: Move towards the right subtree

C#
else {
    root = root.right;
}

If k is greater than the current node value, move to the right subtree.

Step 8: Return the result

C#
return minDifference;

When traversal finishes, return the smallest difference found.

6. Dry Run – Example 1

Input:

Code
root = [10, 2, 11, 1, 5, N, N, N, N, 3, 6, N, 4]
k = 13

BST structure:

Code
          10
         /  \
        2    11
       / \
      1   5
         / \
        3   6
           /
          4

Let's execute the algorithm step by step.

StepCurrent NodeDifferenceMinimum Difference
11033
21122
3NULL—2

Execution:

  • Start at node 10.
  • Calculate Math.Abs(10 - 13) = 3.
  • Since 13 is greater than 10, move right.
  • Reach node 11.
  • Calculate Math.Abs(11 - 13) = 2.
  • Since 13 is greater than 11, move right.
  • Right child is NULL, so traversal stops.

Final answer:

Code
Output: 2

7. Dry Run – Example 2

Input:

Code
root = [8, 1, 9, N, 4, N, 10, 3]
k = 9

BST structure:

Code
        8
       / \
      1   9
       \   \
        4   10
       /
      3

Execution:

StepCurrent NodeDifference
181
290

At node 9:

C#
Math.Abs(9 - 9) = 0;

Since the difference is zero, return immediately.

Code
Output: 0

8. Time and Space Complexity

The expected complexity is O(h) time and O(h) auxiliary space in the problem statement.

However, our iterative implementation uses O(1) auxiliary space.

Time Complexity: O(h)

We visit only one path from the root to a leaf.

  • Balanced BST: O(log n)
  • Skewed BST: O(n)

Auxiliary Space Complexity: O(1)

We use only a few variables:

  • minDifference
  • diff
  • root

We do not use recursion, arrays, lists, or additional data structures.

Here:

  • n = number of nodes.
  • h = height of the BST.

9. Important Interview Questions

Q1. Why do we use a BST instead of normal binary tree traversal?

Because BST ordering allows us to choose either the left or right subtree instead of checking every node.

Q2. Why do we use Math.Abs()?

To calculate the absolute difference without producing a negative value.

Q3. Why initialize minDifference with int.MaxValue?

To ensure that the first calculated difference will always be smaller and can update the minimum.

Q4. Why do we return zero immediately?

Because zero is the minimum possible absolute difference.

Q5. What is the time complexity?

O(h), where h is the height of the BST.

Q6. What is the auxiliary space complexity of this implementation?

O(1), because we use an iterative approach.

10. Key Takeaways

  • Understand the BST property before writing the solution.
  • Use Math.Abs() to calculate the difference.
  • Use Math.Min() to maintain the minimum difference.
  • Move left when k is smaller than the current node.
  • Move right when k is greater than the current node.
  • Return immediately when an exact match is found.
  • Use iterative traversal to achieve O(1) auxiliary space.

Conclusion:

The Closest in BST problem teaches us how to use the Binary Search Tree property to optimize searching. Instead of traversing the entire tree, we follow only the required path and maintain the minimum absolute difference.

This is an important problem for understanding BST searching, tree traversal, and time and space complexity in coding interviews.