The idea is to do Inorder traversal of given binary search tree in an auxiliary array and then by taking absolute difference of each element find the node having minimum absolute difference with given target value K.
Output
1
Using BST Property - O(h) Time and O(1) Space
The idea is to traverse the BST starting from the root and keep track of the closest value to k found so far. At each node, if the current value is closer to k, we update our closest. Depending on whether k is smaller or larger than the current node’s value, we move to the left or right subtree.
Step by Step implementation:
Start with the root node and initialize a variable to store the closest value.
Traverse the BST while the current node is not null.
Update the closest value if the current node’s value is closer to k.
Move to the left subtree if k is smaller, otherwise move to the right subtree.
Return the closest value after traversal completes.
Output
1
Time Complexity: O(h),where h is the height of the BST, as we traverse only one path. Space Complexity: O(1), for the iterative approach, as no extra space is used.