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.
- If the value of root’s key is smaller than k2, then recursively call in the right subtree.
12 20 22
- Time Complexity: O(n), where n is the total number of keys in tree.
A single traversal of the tree is needed.
- Space Complexity: O(1).
No extra space is required.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Print BST keys in given Range | O(1) Space
- Remove BST keys outside the given range
- Remove BST Keys in a given Range
- Convert a BST to a Binary Tree such that sum of all greater keys is added to every key
- BST to a Tree with sum of all smaller keys
- Two nodes of a BST are swapped, correct the BST | Set-2
- K'th Largest Element in BST when modification to BST is not allowed
- Find k-th smallest element in BST (Order Statistics in BST)
- Convert a normal BST to Balanced BST
- Two nodes of a BST are swapped, correct the BST
- Count BST subtrees that lie in given range
- Count BST nodes that lie in a given range
- Find the largest BST subtree in a given Binary Tree | Set 1
- Sorted order printing of a given array that represents a BST
- Construct BST from given preorder traversal | Set 2
- Add all greater values to every node in a given BST
- Construct BST from its given level order traversal
- Find a pair with given sum in BST
- Check given array of size n can represent BST of n levels or not
- Inorder predecessor and successor for a given key in BST | Iterative Approach