Given a binary search tree and a target node K. The task is to find the node with minimum absolute difference with given target value K.
// For above binary search tree Input : k = 4 Output : 4 Input : k = 18 Output : 17 Input : k = 12 Output : 9
A simple solution for this problem is to store 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 in linear time.
An efficient solution for this problem is to take advantage of characteristics of BST. Here is the algorithm to solve this problem :
- If target value K is present in given BST, then it’s the node having minimum absolute difference.
- If target value K is less than the value of current node then move to the left child.
- If target value K is greater than the value of current node then move to the right child.
Time complexity : O(h) where h is height of given Binary Search Tree.
This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Binary Tree to Binary Search Tree Conversion
- Minimum swap required to convert binary tree to binary search tree
- Binary Tree to Binary Search Tree Conversion using STL set
- Difference between Binary Tree and Binary Search Tree
- Find the closest leaf in a Binary Tree
- Binary Search Tree | Set 1 (Search and Insertion)
- Closest leaf to a given node in Binary Tree
- Sum and Product of minimum and maximum element of Binary Search Tree
- Convert a Binary Search Tree into a Skewed tree in increasing or decreasing order
- Count the Number of Binary Search Trees present in a Binary Tree
- Find the node with minimum value in a Binary Search Tree
- Find the node with maximum value in a Binary Search Tree
- Find the node with minimum value in a Binary Search Tree using recursion
- Find the node with maximum value in a Binary Search Tree using recursion
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Check if a binary tree is subtree of another binary tree | Set 1
- Check if a binary tree is subtree of another binary tree | Set 2
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
- Check whether a binary tree is a full binary tree or not