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 in a given Range
- Remove BST keys outside the given range
- AVL with duplicate keys
- BST to a Tree with sum of all smaller keys
- Construct all possible BSTs for keys 1 to N
- Convert a BST to a Binary Tree such that sum of all greater keys is added to every key
- Total number of possible Binary Search Trees and Binary Trees with n keys
- Range LCM Queries
- Count BST nodes that lie in a given range
- Count BST subtrees that lie in given range
- Segment Tree | Set 1 (Sum of given range)
- Segment Tree | Set 3 (XOR of given range)
- Coefficient of Range in a Binary Tree
- XOR of numbers that appeared even number of times in given Range
- Range and Update Query for Chessboard Pieces
- Segment Tree | Set 2 (Range Minimum Query)
- Range Sum Queries and Update with Square Root
- Count elements which divide all numbers in range L-R
- Sum of prime numbers in range [L, R] from given Array for Q queries