Given the root
of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.
For example:
Example 1:
Consider the following BST:
4
/ \
2 6
/ \
1 3
Input: root = [4,2,6,1,3]
Output: 1
Explanation: The minimum difference is between nodes 2 and 3, which is abs(2 - 3) = 1
.
Example 2:
Consider the following BST:
1
/ \
0 48
/ \
12 49
Input: root = [1,0,48,null,null,12,49]
Output: 1
Explanation: The minimum difference is between nodes 1 and 0, which is abs(1 - 0) = 1
.
Constraints:
[2, 100]
. Why at least 2 nodes?0 <= Node.val <= 10^5
How would you approach this problem efficiently, considering the properties of a Binary Search Tree?
The most straightforward approach is to traverse the tree, store the values of all nodes in an array, and then find the minimum difference between any two values in the array.
Code (Python):
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def getMinimumDifference(root):
values = []
def inorder(node):
if not node:
return
inorder(node.left)
values.append(node.val)
inorder(node.right)
inorder(root)
min_diff = float('inf')
for i in range(len(values)):
for j in range(i + 1, len(values)):
min_diff = min(min_diff, abs(values[i] - values[j]))
return min_diff
Time Complexity: O(N2), where N is the number of nodes in the tree. This is because we have nested loops to compare all pairs of values.
Space Complexity: O(N), where N is the number of nodes in the tree. This is due to storing the node values in a list.
Since it's a Binary Search Tree (BST), an inorder traversal will give us the node values in sorted order. We can then find the minimum difference by comparing adjacent values in the sorted order.
Code (Python):
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def getMinimumDifference(root):
min_diff = float('inf')
prev = None
def inorder(node):
nonlocal min_diff, prev
if not node:
return
inorder(node.left)
if prev is not None:
min_diff = min(min_diff, abs(node.val - prev))
prev = node.val
inorder(node.right)
inorder(root)
return min_diff
Time Complexity: O(N), where N is the number of nodes in the tree. We visit each node once during the inorder traversal.
Space Complexity: O(H), where H is the height of the tree. This is due to the recursive call stack during inorder traversal. In the worst case (skewed tree), H can be equal to N, and in the best case (balanced tree), H can be log(N).