Minimum Absolute Difference in BST Problem
Problem
Given the root
of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.
OR
Given the root
of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.
Examples
Example 1:
graph TB; 4 --- 2 & 6; 2 --- 1 & 3;
|
|
Example 2:
graph TB; 1 --- 0 & 48; 48 --- 12 & 49;
|
|
Solution
Method 1 - Inorder Traversal - Two Pass
One way can be we do the inorder traversal, and get the list from it in sorted order, and now compare the difference between 2 elements in the array, and return the min value.
Complexity
- ⏰ Time complexity:
O(n)
where n is tree size - 🧺 Space complexity:
O(n)
, assuming recursion stack and sorted array
Method 2 - Inorder Traversal
Instead of creating the list first, and then find the difference, we can actually track previous node, and calculate the diff with current node in inorder traversal. We also track, the min value and return the min value in the end.
To sum up:
- Perform an in-order traversal of the BST to get a sorted list of node values.
- Calculate the minimum difference between consecutive values in this sorted list.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
where n is tree size - 🧺 Space complexity:
O(h)
, assuming recursion stack