![]() |
VOOZH | about |
Given two values n1 and n2 where n1 < n2 and a root pointer to a Binary Search Tree. The task is to find all the keys of the tree in the range n1 to n2 in increasing order.
Examples:
Input: n1 = 10 , n2 = 22
π print-bst-keys-in-given-rangeOutput: 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: n1 = 1 , n2 = 10
π print-bst-keys-in-given-rangeOutput: 8
Explanation: The key 8 is in the range 1 to 10
Approach:
The idea is to Traverse the tree in the inorder traversal. If the Binary search tree is traversed in inorder traversal the keys are traversed in increasing order. For a given node, if the value of the rootβs key is greater than n2, then recursively call in the left subtree and If node's value is less than n1, then process the right subtree.
Below is the Implementation of the above approach:
12 20 22
Time Complexity: O(n), where n is the total number of keys in the tree.
Auxiliary Space: O(h). where h is the height of the tree.
Related article: