InterviewPrepKit

Home / Coding / Trees

Minimum Absolute Difference in BST

easy Original β†—
Solving tips
  • Key insight: the minimum absolute difference is always between two adjacent values once sorted, so you only need consecutive pairs, never all O(n^2) pairs.
  • In-order traversal of a BST yields values in sorted order for free β€” the answer is the smallest gap between consecutive in-order visits.
  • Carry just a running 'prev' value (no list needed): at each node update best with node.val - prev, then set prev = node.val. O(n) time, O(h) space.
  • Pitfall: guard the first node (prev is None) so you don't compare against a sentinel like 0, which corrupts the answer when all values are large.

Problem

You are 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.

Recall the BST property: for every node, all values in its left subtree are smaller and all values in its right subtree are larger. The two nodes you compare can be anywhere in the tree β€” not just a parent and child.

Examples

Example 1

Input: root = [4,2,6,1,3]
Output: 1

The sorted values are [1,2,3,4,6]. The closest pair is 2 and 3 (or 3 and 4), a difference of 1.

Example 2

Input: root = [1,0,48,null,null,12,49]
Output: 1

Sorted values [0,1,12,48,49]. The closest pair is 0 and 1, difference 1.

Example 3

Input: root = [5,3,8]
Output: 2

Sorted values [3,5,8]; the smallest gap is 5 - 3 = 2.

Constraints

  • The number of nodes is in the range [2, 10^4] (at least two nodes, so an answer always exists).
  • 0 <= Node.val <= 10^5

Think about it first

Hint 1 The minimum absolute difference in any set of numbers is always between two values that are adjacent when the numbers are sorted. So you never need to compare all O(n^2) pairs.
Hint 2 What traversal of a BST visits the nodes in sorted order for free? Once the values come out sorted, the answer is the smallest gap between consecutive ones.
Hint 3 Do an in-order traversal. Keep track of the previously visited value; at each node, update the answer with `node.val - prev`, then set `prev = node.val`. No need to store the whole list.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.