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 Nodes INPUT Binary Search Tree 4 2 6 1 3 root = [4,2,6,1,3] Array representation Left < Node < Right (BST Property) ALGORITHM STEPS 1 Inorder Traversal Visit: Left-Root-Right 2 Sorted Order BST inorder = sorted! Inorder: 1 2 3 4 6 3 Compare Adjacent Track prev node value 2-1 = 1 (min=1) 3-2 = 1 (min=1) 4-3 = 1 (min=1) 6-4 = 2 (min=1) 4 Return Minimum Min diff found = 1 Time: O(n) | Space: O(h) FINAL RESULT Minimum Difference Pairs: 1 -- 2 = 1 2 -- 3 = 1 OUTPUT 1 OK - Minimum Found! |2-1| = |3-2| = 1 Multiple pairs have the same min distance Key Insight: Inorder traversal of a BST produces values in sorted (ascending) order. The minimum difference between any two nodes MUST be between consecutive elements in this sorted sequence. We track the previous node during traversal and compute differences on-the-fly for O(1) extra space. TutorialsPoint - Minimum Distance Between BST Nodes | Inorder Traversal Approach
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