Find the closest element in Binary Search Tree
Given a binary search tree and a target node K. The task is to find the node with a minimum absolute difference with the given target value K.
Input : k = 4
Input : k = 18
Input : k = 12
Find closest element in Binary Search Tree by storing Inorder Traversal:
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.
Time Complexity: O(N)
Auxiliary Space: O(N)
Find closest element in Binary Search Tree using DFS:
Below is the idea to solve the problem:
Traverse the BST starting from root in a way to search the target node, Keep a variable min_dif and update it with the min of min_dif and abs(current node -> data – target node -> data). If current node is greater than the target node then move to the left of current node else move to the right of current node.
Follow the below steps to implement the idea:
- initialize a variable min_dif to store the minimum difference from the target node.
- Traverse the tree starting from root
- If ptr is equal to NULL then return.
- If ptr->key is equal to k then set min_diff_key = 0 and terminate.
- Else if min_diff > abs(ptr->key – k) then set min_diff = abs(ptr->key – k) and set min_diff_key = ptr->key as the pointer to minimum difference node.
- If k < ptr->key then call for ptr->left.
- Else call for ptr->right.
Below is the Implementation of the above approach:
Time complexity: O(H) where h is the height of the given Binary Search Tree.
Auxiliary Space: O(1).
This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Login to comment...