Table of contents
1.
Introduction 🤓
1.1.
Problem Statement 🤔
1.2.
Sample Examples 🧐
2.
Post-Order Traversal Approach💻
2.1.
Algorithm 
2.2.
Implementation 
2.2.1.
Time Complexity ⏳
2.2.2.
Space Complexity 🌌
3.
Frequently Asked Questions 
3.1.
What can counts as a subtree?
3.2.
How many subtrees are there in a binary tree?
3.3.
How can I calculate subtree size?
4.
Conclusion
Last Updated: Mar 27, 2024
Medium

Count BST Subtrees that Lie in a Given Range

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction 🤓

Operation on BST subtrees is a widely asked question in interviews. It is generally asked to check the problem-solving skills and aptitude of candidates. 

introduction

This article will discuss the problem to count BST subtrees that lie in a given range. We will use post order traversal approach to solve this problem. Now let’s get started! 

Count BST Subtrees that Lie in a Given Range

Problem Statement 🤔

The problem is to count BST subtrees that lie in a given range. It is a binary search tree problem. Here we are given the BST of integer value and a range. We have to return the count of the nodes and nodes under other nodes, i.e. subtrees. Which lie in that given range. 

Let’s understand this problem statement with the help of an example.   

Sample Examples 🧐

Example 1: Given Range [10,25]

Input:

input

Output:

output

Explanation:

We have to count BST subtrees that lie in a given range of [10,25]. Here, we find such sub-trees. The subtrees' method is finding the nodes' value in between the given range. And if those nodes have children and their values are in range. Then we count them as sub-trees. 

Example 2: Given range [18,26]

input

Output:

output

Explanation:

We have to count BST subtrees that lie in a given range of [18,26]. Here, we find such sub-trees. The subtrees' method is finding the nodes' value in between the given range. And if those nodes have children and their values are in range. Then we count them as sub-trees.

Post-Order Traversal Approach💻

To solve the problem, count BST subtrees that lie in a given range. We are using a post-order traversal approach. In this approach, we will implement post-order traversal on a given BST. Then for any node, if both of its left and right subtrees are within the range. Along with the node itself. We can say that the subtree associated with this node is also within the range.

approach

Let’s discuss the algorithm of this approach.

Algorithm 

  1. Make a structure to store a BST node.
     
  2. Now create a recursive function to insert a key into a BST. The function will have three cases:
    • If the root value is null. Then create a new node and return it.
    • If the given key is less than the root node value. Then recur for the left subtree.
    • Otherwise, now recur to the right subtree.
       
  3. Now create a function to count subtrees in a BST whose nodes lie within a given range.
     
  4. Return true if the whole subtree rooted at the given node is within range.
     
  5. Initialise the count variable for subtree count.
     
  6. Increase the subtree count by one and return true if the root node, both left and right subtrees, are within the range.

Implementation 

#include <bits/stdc++.h>
using namespace std;
 
// To store a BST node
struct Node
{
    int data;
    Node *left, *right;
 
    Node(int data)
    {
        this->data = data;
        this->left = this->right = nullptr;
    }
};
 
// The recursive function to insert a key into a BST
Node* insertkey(Node* rootnode, int key)
{
    // when the root is null. Create a new node and return it.
    if (rootnode == nullptr) 
    {
        return new Node(key);
    }
 
    // when the given key is less than the root node, recur for the left subtree
    if (key < rootnode->data) 
    {
        rootnode->left = insertkey(rootnode->left, key);
    }
 
    // otherwise, go for the right subtree
    else 
    {
        rootnode->right = insertkey(rootnode->right, key);
    }
 
    // now return root node
    return rootnode;
}
 
// A function to count BST subtrees that lie in a given range. It will return true if the whole subtree rooted at the given node is within range
bool SubTrees(Node* root, int low, int high, int &count)
{
    // base case
    if (root == nullptr) 
    {
        return true;
    }
 
    bool left = SubTrees(root->left, low, high, count);
    bool right = SubTrees(root->right, low, high, count);
 
    // now increasing the subtree count by 1 and return true if the root node, both left and right subtrees are within the given range. 
    if (left && right && (root->data >= low && root->data <= high))
    {
        count++;
        return true;
    }
 
    return false;
}
 
int main()
{
    // the range of input
    int l = 10, h = 25;
 
    // BST keys to construct BST 
    int keys[] = { 20, 30, 25, 27, 35, 23, 15, 13, 14, 17, 11 };
 
    // construct BST
    Node* root = nullptr;
    for (int key: keys) {
        root = insertkey(root, key);
    }
 
    // counting the number of subtrees
    int count = 0;
    SubTrees(root, l, h, count);
   cout << "The count of subtrees in [" << l << ", " << h << "] is " << count;
 
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output:

output

Time Complexity ⏳

The time complexity of the post-order traversal approach. For the problem, count BST subtrees that lie in a given range, is O(n), i.e., linear. Here n is the size of BST. It is because we are traversing the tree in a bottom-up manner. And we are transferring information from children to the parent node.

Space Complexity 🌌

The space complexity of the approach, for the problem, count BST subtrees that lie in a given range, is O(h). It is because this approach will need space proportional to the height of the tree. 

Frequently Asked Questions 

What can counts as a subtree?

A subtree is any node along with its descendants. The root and all its descendants form the entire tree. A uni-valued subtree is therefore a subtree in which all the nodes have the same keys.

How many subtrees are there in a binary tree?

A complete binary tree consists of either a single node (a leaf) or a root node with a left and right subtree. Each of the node which is itself either a leaf or a root node with two subtrees.

How can I calculate subtree size?

We need to calculate subtree size at every node. 

The score of a node = (product of the size of a subtree from every child) * (size of the FULL tree - the size of subtree at the node).

Conclusion

This article briefly discussed the problem, count BST subtrees that lie in a given range. We used post order traversal approach to find the solution to the given problem.

We hope that this blog has helped you enhance your knowledge about the problem count BST subtrees that lie in a given range. And if you would like to learn more, check out our articles Count BST nodes that lie in a given rangeLevel Order Traversal of a Binary TreeConvert BST to the Greatest Sum Tree, and count pairs violating BST properties. You can also refer to our guided path on the basics of java and many more on our Website.

Check out this problem - Connect Nodes At Same Level

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! 

But suppose you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundles for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Happy learning!

Live masterclass