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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code