AlgoInsight

DSA problem

Minimum Absolute Difference in BST

EasyTree Traversal - In OrderPattern: Tree Traversal - In Ordertop300GoogleAmazonMicrosoftBloomberg

Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.

This is the same exercise as "Minimum Distance Between BST Nodes" — the names differ but the algorithm is identical. The reason both exist is mostly historical: LeetCode published the easier version first, then added a follow-up under a different title. The takeaway is the BST's defining invariant gives us all the structure we need.

An inorder traversal of a BST visits node values in strictly increasing order, so the minimum absolute difference between any pair of values must occur between two values that are adjacent in that sorted sequence. Anywhere else in the sequence the gap can only grow, never shrink.

We therefore perform an inorder walk and remember a single value: the previously visited node's value. At each new node we update the running minimum with curr.val - prev (which is non-negative because the sequence is sorted) and then advance prev. This runs in O(n) time and O(h) space — there is no need to materialize the full sorted list.

Examples

Example 1
Input: root = [4,2,6,1,3]
Output: 1
Explanation: Inorder gives [1,2,3,4,6]. Adjacent differences are 1,1,1,2 — the minimum is 1.
Example 2
Input: root = [1,0,48,null,null,12,49]
Output: 1
Explanation: Inorder gives [0,1,12,48,49]. The smallest adjacent absolute difference is 1.
Example 3
Input: root = [236,104,701,null,227,null,911]
Output: 9
Explanation: Inorder gives [104,227,236,701,911]. Adjacent differences are 123,9,465,210 — the minimum is 9.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

bsttree-traversalinorderbinary-tree

Browse all DSA problems