Minimum Absolute Difference in BST (LeetCode 530): Solution and Explanation

Easy
Tree
Depth First Search
Breadth First Search
Binary Search Tree
Binary Tree

Given a binary search tree, find the smallest difference between the values of any two nodes. The tree has at least two nodes and every value is between 0 and 100,000.

Intuition

Comparing every pair of nodes works but costs O(n^2). The BST property gives a much better route.

If the values were in a sorted list, the closest pair would always be two neighbours: any pair that skips over a value in between is at least as far apart as one of the neighbouring pairs inside it.

An inorder traversal of a BST visits values in sorted order. So walk the tree inorder, remember the value visited just before, and compare each node only with that one.

Approach: Inorder traversal with a previous value

  1. Set prev to empty and best to infinity.
  2. Recurse into the left subtree first, so every smaller value is handled before the current node.
  3. At the node, if prev is set, update best = min(best, node.val - prev). The difference is never negative because inorder is increasing.
  4. Set prev = node.val, then recurse into the right subtree.
  5. After the walk, return best.

Step-by-step example

root = [4,2,6,1,3]
  1. Go left from 4 to 2 and from 2 to 1. Node 1 is the smallest value; prev becomes 1.
  2. Back at 2: gap 2 - 1 = 1, so best = 1. prev = 2.
  3. Node 3 (right child of 2): gap 1, best stays 1. prev = 3.
  4. Back at 4: gap 1. Then node 6: gap 2. The sorted order was 1, 2, 3, 4, 6.
  5. Return 1.

Code: Python, Java, C++

1class Solution:
2    def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
3        self.prev = None
4        self.best = float('inf')
5
6        def inorder(node):
7            if not node:
8                return
9            inorder(node.left)
10            if self.prev is not None:
11                self.best = min(self.best, node.val - self.prev)
12            self.prev = node.val
13            inorder(node.right)
14
15        inorder(root)
16        return self.best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Inorder traversal with a previous value O(n)
Collect values, then scan O(n)
Morris inorder traversal O(n)
Sort all values from any traversal O(n log n)
Time

O(n)

Each node is visited once and does a constant amount of work.

Space

O(h)

Only the recursion stack is used, which is as deep as the tree height h: O(log n) when balanced, O(n) for a chain.

Other approaches

Collect values, then scan (time O(n), space O(n))

Write the inorder sequence to an array and take the minimum difference of neighbours. Simple, but stores all n values.

Morris inorder traversal (time O(n), space O(1))

Thread the tree temporarily so the inorder walk needs no stack, then restore it. Constant extra space, more intricate code.

Sort all values from any traversal (time O(n log n), space O(n))

Ignores the BST property: gather values in any order, sort them, and scan neighbours.

Common mistakes

  • Comparing a node only with its direct children. The closest value can be far away in the tree, for example the largest value in the left subtree.
  • Using 0 as the 'no previous value' sentinel, since 0 is a valid node value.
  • Keeping prev and best as fields without resetting them, so a second call reuses the first call's state.
  • Taking an absolute value is harmless but unnecessary: in inorder order node.val - prev is never negative.

Frequently asked questions

Why is it enough to compare neighbours in sorted order?

For sorted values a < b < c, c - a = (c - b) + (b - a), which is larger than either neighbouring gap. So the minimum over all pairs is always a neighbouring pair.

Is this the same as Minimum Distance Between BST Nodes?

Yes. LeetCode 783 asks the same question with a smaller size limit, and the same inorder solution solves both.

Would this work on a plain binary tree?

No. Without the BST ordering, inorder is not sorted. You would need to collect and sort the values first, which costs O(n log n).