Minimum Absolute Difference in BST - Problem

You're given the root of a Binary Search Tree (BST) and need to find the smallest possible absolute difference between the values of any two different nodes in the entire tree.

Think of it as finding the two nodes whose values are closest together when you ignore the sign of their difference. For example, if you have nodes with values 2 and 5, the absolute difference is |2-5| = 3.

Goal: Return the minimum absolute difference as an integer.

Input: The root node of a BST

Output: An integer representing the minimum absolute difference

Key Insight: Since this is a BST, an in-order traversal will give you all values in sorted order, making it easier to find consecutive differences!

Input & Output

example_1.py โ€” Basic BST
$ Input: root = [4,2,6,1,3]
โ€บ Output: 1
๐Ÿ’ก Note: The tree has values [1,2,3,4,6]. The minimum differences are |2-1|=1, |3-2|=1, and |4-3|=1, so the answer is 1.
example_2.py โ€” Simple BST
$ Input: root = [1,0,48,null,null,12,49]
โ€บ Output: 1
๐Ÿ’ก Note: The tree contains values [0,1,12,48,49]. The minimum differences are |1-0|=1 and |49-48|=1, so the answer is 1.
example_3.py โ€” Two Node Tree
$ Input: root = [90,69]
โ€บ Output: 21
๐Ÿ’ก Note: With only two nodes having values 90 and 69, the minimum (and only) absolute difference is |90-69| = 21.

Visualization

Tap to expand
๐ŸŽฏ BST In-Order Magic๐Ÿ“š Library AnalogyID101ID102ID103ID104ID106diff = 1diff = 1diff = 1diff = 2Only compare adjacent books!42613In-order: 1 โ†’ 2 โ†’ 3 โ†’ 4 โ†’ 6โšก Optimal Algorithm1. In-order traversal = sorted order2. Compare only with previous node3. Time: O(n), Space: O(h)โœ“ No extra array needed!๐Ÿ† Result1
Understanding the Visualization
1
Start from Leftmost
Begin in-order traversal from the smallest value (leftmost node)
2
Compare Adjacent
For each subsequent node, compare only with the previously visited node
3
Track Minimum
Keep updating the minimum difference as you traverse
4
Complete Traversal
Finish the in-order traversal with the guaranteed minimum difference
Key Takeaway
๐ŸŽฏ Key Insight: BST in-order traversal gives us sorted values, so we only need to check consecutive pairs instead of all possible pairs!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

We visit each node exactly once during the in-order traversal

n
2n
โœ“ Linear Growth
Space Complexity
O(h)

Only recursion stack space needed, where h is the height of the tree (O(log n) for balanced BST, O(n) for skewed tree)

n
2n
โœ“ Linear Space

Constraints

  • The number of nodes in the tree is in the range [2, 104]
  • 0 โ‰ค Node.val โ‰ค 105
  • The tree is guaranteed to be a valid BST
Asked in
Google 42 Amazon 38 Microsoft 31 Meta 24
68.2K 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