Saturday, February 4, 2012

Print BST keys within a given range

Given two values k1 and k2 (where k1 < k2) and a root pointer to a Binary Search Tree. Print all the keys of tree in range k1 to k2. i.e. print all x such that k1<=x<=k2 and x is a key of given BST. Print all the keys in increasing order.
For example, if k1 = 10 and k2 = 22, then your function should print 12, 20 and 22.
                                       20
                                   /         \
                                 8           22
                             /     \
                           4      12
http://www.geeksforgeeks.org/print-bst-keys-in-the-given-range/

Strategy:
1) If value of root’s key is greater than k1, then recursively call in left subtree.
2) If value of root’s key is in range, then print the root’s key.
3) If value of root’s key is smaller than k2, then recursively call in right subtree.

Note:Here k1 is min value and k2 is max value in the range given

Code: 
void PrintBSTKeys(struct node *root, int k1, int k2)
{
   if ( NULL == root )
      return;
   if ( k1 < root->data )
     PrintBSTKeys(root->left, k1, k2)
   if ( k1 <= root->data && k2 >= root->data )
     printf("%d ", root->data );
   if ( k2 > root->data )
     PrintBSTKeys(root->right, k1, k2);
}
Time Complexity:O(n)

No comments:

Post a Comment