InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Minimum Absolute Difference in BST

easy Original ↗ 00:00

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? 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug