Problem Description
Given the root of a binary search tree (BST) and a target value, the task is to return the value in the BST that is closest to the target. If there are multiple closest values (i.e. same absolute distance), return the smallest value among them.
Key Insights
- BST property allows us to traverse the tree efficiently by comparing the target with node values.
- We can iteratively traverse the tree, moving left if the target is smaller than the current node’s value and moving right if greater.
- At each node, calculate the absolute difference between node's value and the target, and update the answer if the difference is smaller—or equal with a smaller candidate value.
- This approach minimizes the search area by leveraging the inherent ordering in BSTs.
Space and Time Complexity
Time Complexity: O(h) on average, where h is the height of the tree (O(log n) for a balanced tree, and O(n) in the worst-case scenario for a skewed tree).
Space Complexity: O(1) for an iterative solution (or O(h) if using recursion due to the call stack).
Solution
We solve the problem by performing an iterative traversal of the BST. Starting at the root, we maintain a variable to store the value closest to the target. For every node encountered, we:
- Compute the absolute difference between the node’s value and the target.
- Update the stored closest value if the computed difference is less than the current smallest difference; if the difference is the same, choose the smaller node value.
- Depending on whether the target is less than or greater than the current node's value, move to the left or right child accordingly. This approach efficiently defines a search path that is consistent with the properties of a BST.