Minimum Absolute Difference in BST

EasyBinary Search Tree · In-order Traversal🧩 Binary Search Tree & In-orderLeetCode #530 ↗Updated

Problem

You are given the root of a binary search tree with at least two nodes. Among all pairs of different nodes, find the smallest absolute difference between their values and return it.
Inputroot = [4,2,6,1,3]Output1
Inputroot = [1,0,48,null,null,12,49]Output1
Inputroot = [10,null,90]Output80

2 ≤ nodes ≤ 104  ·  0 ≤ Node.val ≤ 105

Try it yourself

Java
class Solution {
    public int getMinimumDifference(TreeNode root) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
An in-order walk of a BST visits values in sorted order, and in a sorted list the closest pair is always adjacent. So remember only the previously visited value and compare it with the current one.
PatternBinary Search Tree & In-order

Instinct The tree is a BST? Its in-order walk is a sorted list and every node splits the search space - think "sorted array in tree form", not "visit everything".

Memory hack Left is less, right is more, in-order reads the sorted score - and every node lives inside a (low, high) fence set by its ancestors.

Open the Binary Search Tree & In-order guide →

Approaches

Brute ForceCollect Values, Check Every Pair

Time O(n²)Space O(n)

Gather all values with any traversal, then compare each pair (i, j) and keep the smallest |a − b|. It never uses the BST ordering, so every pair has to be inspected.

Java
public int getMinimumDifference(TreeNode root) {
    List<Integer> vals = new ArrayList<>();
    collect(root, vals);
    int best = Integer.MAX_VALUE;
    for (int i = 0; i < vals.size(); i++)
        for (int j = i + 1; j < vals.size(); j++)
            best = Math.min(best, Math.abs(vals.get(i) - vals.get(j)));
    return best;
}
private void collect(TreeNode node, List<Integer> vals) {
    if (node == null) return;
    vals.add(node.val);
    collect(node.left, vals);
    collect(node.right, vals);
}

Obviously correct, but quadratic: 104 nodes means ~5·107 pairs.

At a glance

LevelApproachTimeSpace
Brute ForceCollect Values, Check Every PairO(n²)O(n)
BetterIn-order List + Adjacent GapsO(n)O(n)
OptimalIn-order with a Previous PointerO(n)O(h)
Common pitfalls
  • Comparing each node only with its own children — the closest value can be far away in the tree (e.g. root vs. a deep leaf).
  • Initialising prev to a sentinel like Integer.MIN_VALUE and subtracting → overflow.
  • Keeping prev as a method parameter: it must carry over between subtrees, so use a field or a holder.
Interview tips
  • Say the key fact out loud: in-order of a BST is sorted, and the minimum gap lies between neighbours.
  • Point out the O(n) list version first, then remove the list.
  • Mention Morris traversal if asked for O(1) extra space.
Pattern
BST in-order = sorted stream → any question about sorted neighbours, k-th smallest, or validation in a BST.
My notes saved in this browser