Find Closest Element in Binary Search Tree
The problem of finding a closest element in a tree to a given value is another case where we can use the property of binary search tree.
Problem statement
Given a Binary Search Tree and a value, find the closest element to the given value in BST.
Analysis
Simple approach is to go to all elements of BST and find out the difference between the given value and value of the element. Get the minimum value and add or subtract that minimum value from the given value, we would get the closest element in the BST.
Do we really need to scan all the nodes? No we don't need to.
Let's consider it case by case.
Case 1 : If the value of the node under consideration is equal to value, then our minimum difference would be zero and closest value would the value itself.
Case 2 : If the value of the node under consideration is greater than given value.
By virtue of BST, we know that nodes on the right side of the given node would be greater than this. Hence the difference between the given value and all nodes on the right side would only increase. Hence there is no element on the right side, which is closer than the node itself. Hence the right sub tree is discarded.
Case 3 : If the value of the node under consideration is less than the given value.
Again same logic applies as in case 2. Since all elements in left sub tree are less than the node, difference between given value and the nodes on left side would only increase. Hence we can safely discard the left sub tree.
Algorithm
- Start from the root, initialize min to MAX_INT