Given a BST, count the total number of nodes that lie within a given range.

For example, the total number of nodes in range [12, 20] in the following BST is 4. The nodes are 12, 15, 18, and 20.

Count Subtrees in the BST

Practice this problem

A simple solution is to traverse the BST using any of the tree traversals (inorder, preorder, or postorder) and compare each node with the given range. If the current node is within the given range, increment the result’s count. Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

The total number of nodes is 4

Java


Download  Run Code

Output:

The total number of nodes is 4

Python


Download  Run Code

Output:

The total number of nodes is 4

The time complexity of the above solution is O(n), where n is the total number of nodes in the BST. The auxiliary space required by the program is O(h) for the call stack, where h is the BST height.

 
The above solution traverses the whole of BST. We can improve the running time by discarding the left half or the right half if no solution feasible. The idea is to traverse the BST and compare each node with the given range. Then,

  • If the root node lies within the current range, increment the result’s count and recur for both of its children.
  • If the root node is less than the minimum value in the range, discard the left half and recur for only the right subtree.
  • If the root node is more than the maximum value in the range, discard the right half and recur for only the left subtree.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The total number of nodes is 4

Java


Download  Run Code

Output:

The total number of nodes is 4

Python


Download  Run Code

Output:

The total number of nodes is 4