Code Logo

BST Range Query

Published at25 Jul 2026
Binary Search Tree Easy 0 views
Like0

Given a sorted array representing a BST's inorder traversal and a range [low, high], count how many values in the BST fall within the range (inclusive).

Since the array is sorted, iterate through and count values between low and high inclusive.

Example Input & Output

Example 1
Input
[1,2,3,4,5],2,4
Output
3
Explanation

Values 2,3,4 are in range [2,4]

Example 2
Input
[10,20,30,40,50],25,35
Output
1
Explanation

Only 30 is in range

Example 3
Input
[],1,5
Output
0
Explanation

Empty

Example 4
Input
[1,2,3],0,10
Output
3
Explanation

All in range

Example 5
Input
[5,10,15],20,30
Output
0
Explanation

None in range

Algorithm Flow

Recommendation Algorithm Flow for BST Range Query
Recommendation Algorithm Flow for BST Range Query

Solution Approach

function solution(arr, low, high) {
  var count = 0;
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] >= low && arr[i] <= high) count++;
  }
  return count;
}

Best Answers

java
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;
    }
}