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:
Input:
root = [10, 2, 11, 1, 5, N, N, N, N, 3, 6, N, 4]
k = 13
Output:
2Explanation:
The closest node value to 13 is 11.
|11 - 13| = 2Therefore, 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:
- All values in the left subtree are smaller than the root.
- All values in the right subtree are greater than the root.
- Both left and right subtrees must also follow BST rules.
Example:
10
/ \
5 15
/ \ / \
2 7 12 20If 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:
- Initialize
minDifferencewithint.MaxValue. - Start traversing from the root.
- Calculate the absolute difference between the current node value and
k. - Compare the current difference with
minDifference. - Update
minDifferenceif the current difference is smaller. - If the difference is zero, return zero immediately.
- If
kis smaller than the current node value, move to the left child. - Otherwise, move to the right child.
- Continue until the current node becomes null.
- Return the minimum difference.
4. C# Implementation
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
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
while (root != null)We continue traversing until there are no more nodes to visit in the selected search path.
Step 3: Calculate absolute difference
int diff = Math.Abs(root.data - k);Math.Abs() returns the positive difference between two numbers.
Example:
root.data = 10;
k = 13;
diff = Math.Abs(10 - 13);
// Result: 3Step 4: Update the minimum difference
minDifference = Math.Min(minDifference, diff);Math.Min() returns the smaller of the two values.
For example:
Current minimum = 3
New difference = 2
Updated minimum = 2Step 5: Check for an exact match
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
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
else {
root = root.right;
}If k is greater than the current node value, move to the right subtree.
Step 8: Return the result
return minDifference;When traversal finishes, return the smallest difference found.
6. Dry Run – Example 1
Input:
root = [10, 2, 11, 1, 5, N, N, N, N, 3, 6, N, 4]
k = 13BST structure:
10
/ \
2 11
/ \
1 5
/ \
3 6
/
4Let's execute the algorithm step by step.
| Step | Current Node | Difference | Minimum Difference |
|---|---|---|---|
| 1 | 10 | 3 | 3 |
| 2 | 11 | 2 | 2 |
| 3 | NULL | — | 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:
Output: 27. Dry Run – Example 2
Input:
root = [8, 1, 9, N, 4, N, 10, 3]
k = 9BST structure:
8
/ \
1 9
\ \
4 10
/
3Execution:
| Step | Current Node | Difference |
|---|---|---|
| 1 | 8 | 1 |
| 2 | 9 | 0 |
At node 9:
Math.Abs(9 - 9) = 0;Since the difference is zero, return immediately.
Output: 08. 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:
minDifferencediffroot
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
kis smaller than the current node. - Move right when
kis 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.


Join the conversation! Your thoughts help the community grow.