Given a BST, count subtrees in it whose nodes lie within a given range.

For example, consider the following BST. The total number of subtrees with nodes in range [5, 20] is 6.

Count Subtrees in the BST

 
The subtrees are:

  6        9          8            10         12         18
                    /  \          /  \
                   6    9        8    12
                                / \
                               6   9

Practice this problem

A simple solution would be to traverse the tree and, for each encountered node, check if all nodes under the subtree rooted under the node are within the given range or not. The time complexity of this solution is O(n2) for a binary search tree with n nodes. We can improve time complexity to linear by traversing the tree in a bottom-up manner and transfer some information from children to the parent node.

 
The idea is to perform a postorder traversal on the given BST. Then for any node, if both its left and right subtrees are within the range along with the node itself, we can say that the subtree rooted with this node is also within the range.

The algorithm can be implemented as follows in C++, Java, and Python. In C++ solution, we maintain a reference variable to store the subtrees count. In Java code, the AtomicInteger class is used to return multiple values from the function. And in the python code, tuples are being used for the same.

C++


Download  Run Code

Output:

The total number of subtrees is 6

Java


Download  Run Code

Output:

The total number of subtrees is 6

Python


Download  Run Code

Output:

The total number of subtrees is 6

The time complexity of the above solution is O(n), where n is the size of the BST, and requires space proportional to the tree’s height for the call stack.