Print BST keys in the 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 the 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.
Graph: Input: k1 = 10 and k2 = 22 Output: 12, 20 and 22. Explanation: The keys are 4, 8, 12, 20, and 22. So keys in range 10 to 22 is 12, 20 and 22. Input: k1 = 1 and k2 = 10 Output: 4 and 8 Explanation: The keys are 4, 8, 12, 20, and 22. So keys in range 1 to 10 is 4 and 8.
Approach: Traverse the tree in the inorder traversal. If the Binary search tree is traversed in inorder traversal the keys are traversed in increasing order. So while traversing the keys in the inorder traversal. If the key lies in the range print the key else skip the key.
- Create a recursive function that takes root as a parameter and the range is (k1, k2)
- If the value of root’s key is greater than k1, then recursively call in left subtree.
- If the value of root’s key is in range, then print the root’s key.
- recursively call the right subtree.