Problem Description
Given the root of a Binary Search Tree (BST), you need to determine the minimum difference between values of any two different nodes in the tree.
Key Insights
- The in-order traversal of a BST produces a sorted list of node values.
- The minimum difference will be found between two consecutive values in this sorted sequence.
- Use a variable to track the previous node value during traversal.
- Update the minimum difference as you visit each node.
Space and Time Complexity
Time Complexity: O(n), where n is the number of nodes in the BST, since every node is visited once. Space Complexity: O(n) in the worst-case scenario due to recursion stack (or O(h) where h is the tree height for balanced trees).
Solution
The solution uses an in-order traversal of the BST to get the nodes in a sorted order. As we traverse the tree, we maintain a variable to store the previous node's value. The absolute difference between the current node's value and the previous node's value is computed, and if it is smaller than the current minimum difference, it is updated. This approach leverages the BST's inherent characteristics and ensures that the minimum difference is found efficiently.