Ad

Showing posts with label Binary Search Tree. Show all posts
Showing posts with label Binary Search Tree. Show all posts

Sunday, 23 June 2013

Algo#23 Search given key in BST, if not present return next higher value than key which is present

Search given key in BST, if not present return next higher value than key which is present.

If we think just for a while, we will come to know that it is nothing but modified search in BST only. We have to maintain node when ever we are taking left turn in BST. Thats it. Done. Why it will work like this? Because if we are going right side, it means our key is grater than value at current node. So we don't need that value which is less than our key.

Following is implementation of above algorithm in c language.





Please write comments if you find anything wrong or you want to add something more related to this topic.

Friday, 7 June 2013

Algo#7: Closest Value Search in Binary Search Tree (BST)

Closest Value Search in Binary Search Tree (BST) means returning nearest value in BST to given key.

Following is simple algorithm for finding Closest Value in BST.
Step 1: Current root itself is NULL, then closest value is zero.
Step 2: If current root matches target key value, then closest value is key itself.
Step 3: Otherwise, consider current root as closest value and do following.
        3.1: If key is smaller then current root, find closest value on left side tree of current root recursively and call it RecursiveClosest.
        3.2: If key is larger then current root, find closest value on right side tree of current root recursively and call it RecursiveClosest.
Step 4: Return current root or RecusiveClosest depending on which ever is nearer to target key.


Following is implementation of above algorithm in c language.





Please write comments if you find anything wrong or you want to add something more related to this topic.

Ad