Minimum Absolute Difference in a BST
Find the smallest absolute difference between the values of any two distinct nodes in a binary search tree.
Given the root of a binary search tree (BST) with at least two nodes, return the minimum absolute difference between the values of any two distinct nodes in the tree.
Example 1
Input: root = [5,3,8,2,4,7,9]
Output: 1
Explanation: In sorted order the values are 2, 3, 4, 5, 7, 8, 9. The adjacent differences are 1, 1, 1, 2, 1, 1 -- the minimum is 1.
Example 2
Input: root = [10,3,20,null,9]
Output: 1
Explanation: In sorted order the values are 3, 9, 10, 20. The minimum difference (1) occurs between 9 and 10, which are not parent and child.
Example 3
Input: root = [4,2]
Output: 2
Constraints
- The tree contains at least 2 nodes.
- 0 <= Node.val <= 1000000
- root is guaranteed to be a valid binary search tree.
- All node values are unique.
Hints
Companies
No companies reported yet.
Discussion
Sign in to join the discussion.
Loading discussion...
Test results
No test cases yet.