A simple solution mentioned in this post uses recursion to get the closest element to a key in Binary search tree. The method used in the above mentioned post consumes O(n) extra space due to recursion.
Now we can easily modify the above mentioned approach using Morris traversal which is a space efficient approach to do inorder tree traversal without using recursion or stack/queue in constant space O(1).
Morris traversal is based on Threaded Binary trees which makes use of NULL pointers in a tree to make them point to some successor or predecessor nodes. As in a binary tree with n nodes, n+1 NULL pointers waste memory.
In the algorithm mentioned below we simply do inorder tree traversal and while doing inorder tree traversal using Morris Traversal we check for differences between the node’s data and the key and maintain two variables ‘diff’ and ‘closest’ which are updated when we find a closer node to the key. When we are done with the complete inorder tree traversal we have the closest node.
1) Initialize Current as root.
2) Initialize a variable diff as INT_MAX.
3)initialize a variable closest(pointer to node) which
will be returned.
4) While current is not NULL:
4.1) If the current has no left child:
a) If the absolute difference between current's data
and the key is smaller than diff:
1) Set diff as the absolute difference between the
current node and the key.
2) Set closest as the current node.
b)Otherwise, Move to the right child of current.
4.2) Else, here we have 2 cases:
a) Find the inorder predecessor of the current node.
Inorder predecessor is the rightmost node
in the left subtree or left child itself.
b) If the right child of the inorder predecessor is NULL:
1) Set current as the right child of its inorder
predecessor(Making threads between nodes).
2) Move current node to its left child.
c) Else, if the threaded link between the current node
and it's inorder predecessor already exists :
1) Set right pointer of the inorder predecessor node as NULL.
2) If the absolute difference between current's data and
the key is smaller than diff:
a) Set diff variable as the absolute difference between
the current node and the key.
b) Set closest as the current node.
3) Move current to its right child.
5)By the time we have traversed the whole tree, we have the
closest node, so we simply return closest.
Please Login to comment...