Full and complete answer in order to get credit thank you Le

Full and complete answer in order to get credit. thank you.

Let T be a binary search tree (BST) of height h. Design an algorithm which prints all the keys in T whose values are between v1 and v2 (v1 < v2). If there are m keys in this range, then your algorithm should run in O(m + h) time.

Solution

I have added explanation in between the Algorithm, read it to understand more better.

We pass the Root of BST and two values v1 and v2. the output is m keys and The Time complexity is O(m+h)


Algorithm KeysWithinRange( root, v1, v2)

Start

   if root==null

      return

   /* Since the desired output is sorted, recurse for left subtree first

      If root.data is greater than v1, then only we can get output keys

      in left subtree */

   if v1 < root.data

     KeysWithinRange(root.left, v1, v2)

   /* if root\'s data lies in range, then Output root\'s data */

   if ( v1 <= root.data && v2 >= root.data )

     Output   root.data

  /* If root.data is smaller than v2, then only we can get output keys

      in right subtree */

   if v2 > root.data

     KeysWithinRange(root.right, v1, v2);

End




Thanks, let me know if there is any concern.

Full and complete answer in order to get credit. thank you. Let T be a binary search tree (BST) of height h. Design an algorithm which prints all the keys in T

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site