Problem Description
Given the root of a Binary Search Tree (BST), find and return the minimum absolute difference between the values of any two different nodes in the tree.
Key Insights
- Inorder traversal of a BST yields the node values in sorted order.
- The minimum absolute difference will always be between two consecutive values in this sorted order.
- A single traversal (inorder) is sufficient to compute the answer by comparing the current node’s value with the previous node’s value.
- Using an extra variable to store the previous node’s value avoids the need for extra space to store the sorted list.
Space and Time Complexity
Time Complexity: O(n), where n is the number of nodes in the BST. Space Complexity: O(n) in the worst-case for the call stack (tree height) for a skewed tree; O(log n) on average for a balanced tree.
Solution
The solution performs an inorder traversal of the BST to retrieve the node values in sorted order. During the traversal, it keeps track of the previously visited node’s value. At each node, the difference between the current node’s value and the previous node’s value is computed, and the minimum difference is updated accordingly. This method leverages the BST’s inherent property of ordered traversal to efficiently calculate the desired result without additional data structures.