Minimum Distance Between BST Nodes - Problem

Given the root of a Binary Search Tree (BST), find the minimum absolute difference between the values of any two different nodes in the tree.

A Binary Search Tree guarantees that for every node, all values in the left subtree are smaller and all values in the right subtree are larger. This property can be leveraged to solve the problem efficiently!

Goal: Return the smallest possible difference between any two node values.

Example: In a BST with values [4, 2, 6, 1, 3], the minimum difference would be 1 (between nodes 2 and 3, or 2 and 1).

Input & Output

example_1.py โ€” Basic BST
$ Input: root = [4,2,6,1,3]
โ€บ Output: 1
๐Ÿ’ก Note: The minimum difference is between nodes 1 and 2, or 2 and 3, or 3 and 4, all giving a difference of 1.
example_2.py โ€” Larger differences
$ Input: root = [1,0,48,null,null,12,49]
โ€บ Output: 1
๐Ÿ’ก Note: The minimum difference is between nodes 48 and 49, giving a difference of 1.
example_3.py โ€” Two-node tree
$ Input: root = [1,null,3]
โ€บ Output: 2
๐Ÿ’ก Note: Only two nodes exist: 1 and 3, so the minimum (and only) difference is 2.

Constraints

  • The number of nodes in the tree is in the range [2, 104]
  • 0 โ‰ค Node.val โ‰ค 105
  • Important: The tree is guaranteed to be a valid Binary Search Tree

Visualization

Tap to expand
BST Inorder Traversal = Sorted Sequence503070204080Inorder Traversal Path:203040507080Adjacent Differences:30-20=1040-30=1050-40=1070-50=2080-70=10Key Insightโœ“ Inorder traversal visits nodes in sorted orderโœ“ Minimum difference occurs between adjacent valuesโœ“ Result: min_diff = 10
Understanding the Visualization
1
BST Structure
Left subtree < root < right subtree for every node
2
Inorder Sequence
Left โ†’ Root โ†’ Right visits nodes in ascending order
3
Adjacent Minimum
In sorted sequence, minimum difference is always between adjacent elements
Key Takeaway
๐ŸŽฏ Key Insight: BST inorder traversal produces a sorted sequence, so we only need to compare adjacent values to find the minimum difference!
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
38.2K Views
Medium Frequency
~15 min Avg. Time
1.7K 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