VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-bst-nodes-that-are-in-a-given-range/

⇱ Count BST nodes that lie in a given range - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count BST nodes that lie in a given range

Last Updated : 23 Jul, 2025

Given a Binary Search Tree (BST) and a range [l, h], the task is to count the number of nodes in the BST that lie in the given range.


Examples:

Input:

👁 Count-BST-nodes-that-lie-in-a-given-range

Output:  3
Explanation: There are three nodes in range [5, 45] = 5, 10 and 40.

Input:

👁 Count-BST-nodes-that-lie-in-a-given-range_1

Output:  4
Explanation: There are four nodes in range [10, 100] = 10, 40, 50 and 100.

[Expected Approach] Using Recursion - O(n) Time and O(h) Space

The idea is traverse the given binary search tree starting from root. For every node check if this node lies in range, if yes, then add 1 to result and recursively check for both of its children. If current node is smaller than low value of range, then recur for right child, else recur for left child.

Follow the below steps to Implement the idea:

  • Traverse the tree starting from the root.
    • If root->data is equal to high and root->data is equal to low return 1.
    • If root->data <= high and root->data >= low then return 1 + count on left of root + count on right of root.
    • Else if root->data < low return count on right of root.
    • Else if root->data > high return count on left of root.

Below is the implementation of the above approach.  


Output
3

[Alternate Approach] Using Queue - O(n) Time and O(n) Space

The idea is traverse the given binary search tree in level order manner using a queue. For every node check if this node lies in range, if yes, then add 1 to result and push both of its children into queue. If current node is smaller than low value of range, then push right child, else push left child.

Below is the implementation of the above approach:


Output
3
Comment
Article Tags: