Intuition
An in-order traversal of a BST visits values in sorted order, so the closest pair must be adjacent in that sequence. Track the previous value and take the smallest gap between consecutive visits.
Explanation
Idea
In a BST, an in-order traversal (left, node, right) yields the node values in ascending order. In a sorted sequence, the minimum absolute difference always occurs between two adjacent elements — so we never need to compare far-apart nodes. Keep the previously visited value and minimize the gap as we go.
Algorithm
- Traverse the tree in-order, keeping
prev(the last value seen) andbest(∞). - At each node, if
prevexists, updatebest = min(best, node.val - prev). - Set
prev = node.valand continue. - Return
best.
Worked example: [4,2,6,1,3]
4
/ \
2 6
/ \
1 3
In-order sequence: 1, 2, 3, 4, 6. Adjacent gaps: 1, 1, 1, 2. The minimum is 1.
Complexity
- Time: O(n) — each node visited once.
- Space: O(h) for the traversal stack/recursion.
Implementation
class Solution {
private Integer prev = null;
private int best = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
inorder(root);
return best;
}
private void inorder(TreeNode node) {
if (node == null) {
return;
}
inorder(node.left);
if (prev != null) {
best = Math.min(best, node.val - prev);
}
prev = node.val;
inorder(node.right);
}
}