Minimum Distance Between BST Nodes - Problem

Given the root of a Binary Search Tree (BST), return the minimum 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

Note: The minimum difference is always positive since we're looking at different nodes.

Input & Output

Example 1 — Basic BST
$ Input: root = [4,2,6,1,3]
Output: 1
💡 Note: Inorder traversal gives [1,2,3,4,6]. Adjacent differences: |2-1|=1, |3-2|=1, |4-3|=1, |6-4|=2. Minimum is 1.
Example 2 — Larger Gaps
$ Input: root = [1,0,48,null,null,12,49]
Output: 1
💡 Note: Inorder traversal 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 — Small Tree
$ Input: root = [1,null,3]
Output: 2
💡 Note: Inorder traversal gives [1,3]. Only one difference: |3-1|=2.

Constraints

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

Visualization

Tap to expand
Minimum Distance Between BST Nodes4261312346Inorder Traversal: 1 → 2 → 3 → 4 → 6Adjacent Differences: 1, 1, 1, 2Minimum Distance: 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
Find Minimum
Minimum consecutive difference is 1
Key Takeaway
🎯 Key Insight: BST inorder traversal automatically gives sorted values, making it easy to find minimum consecutive differences
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
71.8K Views
Medium Frequency
~15 min Avg. Time
1.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