BST Range Query
Given an array representing a Binary Search Tree (BST) in level-order and two integers low and high, return an array of all values in the BST that fall within the inclusive range [low, high].
For example, in the BST [5, 3, 8, 1, 4, 7, 9] with range [3, 7], the result is [3, 4, 5, 7] (sorted). If no values fall in the range, return []. An empty tree returns [].
Range queries are a common BST operation used in database indexing, geographic information systems, and interval searching. The BST property allows efficient range queries by pruning subtrees that cannot contain values in the target range. If the current node is less than low, the entire left subtree can be skipped; if greater than high, the right subtree can be skipped.
For the array-based representation, perform a traversal starting at index 0. If the current node's value is within [low, high], add it to the result. Recursively traverse both children unless the current value is outside the range, in which case you can prune one side.
Edge cases include an empty tree (return []), a range where no values match (return []), low == high (return values exactly equal to that), and very wide ranges that include all nodes (return the full tree in sorted order).
Example Input & Output
Values 2,3,4 are in range [2,4]
Only 30 is in range
Empty
All in range
None in range
Algorithm Flow
Solution Approach
Traverse the BST and collect values within the range, pruning subtrees that cannot contain valid values.
Define a recursive function that visits nodes. If the current value is greater than low, traverse the left subtree (it may contain valid values). If the current value is within range, add it. If the current value is less than high, traverse the right subtree. Start at index 0.
Time complexity is O(n) worst case (when all nodes are in range). Space complexity is O(n) for the result and recursion stack.
Best Answers
class Solution {
public int solution(int[] nums, int l, int h) {
int c=0;for(int n:nums){if(n>=l&&n<=h)c++;}return c;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
