Minimum Absolute Difference in BST - Problem

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.

A BST is a binary tree where for every node:

  • All values in the left subtree are less than the node's value
  • All values in the right subtree are greater than the node's value

The absolute difference between two values a and b is |a - b|.

Input & Output

Example 1 — Basic BST
$ Input: root = [4,2,6,1,3]
Output: 1
💡 Note: The tree has values 4,2,6,1,3. Inorder traversal gives [1,2,3,4,6]. Adjacent differences are: 2-1=1, 3-2=1, 4-3=1, 6-4=2. Minimum is 1.
Example 2 — Small BST
$ Input: root = [1,0,48,null,null,12,49]
Output: 1
💡 Note: The tree has values 1,0,48,12,49. Inorder gives [0,1,12,48,49]. Adjacent differences: 1-0=1, 12-1=11, 48-12=36, 49-48=1. Minimum is 1.
Example 3 — Two Nodes
$ Input: root = [1,null,3]
Output: 2
💡 Note: Only two nodes with values 1 and 3. The absolute difference is |3-1| = 2.

Constraints

  • The number of nodes in the tree is in the range [2, 104]
  • 0 ≤ Node.val ≤ 105

Visualization

Tap to expand
BST Property: Inorder Traversal Gives Sorted ValuesInput BST:42613Inorder Traversal:123462-1=13-2=14-3=16-4=2Minimum Difference: 1
Understanding the Visualization
1
Input BST
Binary Search Tree with values [4,2,6,1,3]
2
Inorder Traversal
BST inorder gives sorted sequence: 1→2→3→4→6
3
Adjacent Differences
Minimum difference is between consecutive values: min(1,1,1,2) = 1
Key Takeaway
🎯 Key Insight: BST inorder traversal gives sorted values, so minimum difference is always between adjacent elements
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
189.0K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen