Count of nodes in a binary tree having their nodes in range [L, R]
Given a Binary Tree consisting of N nodes and two positive integers L and R, the task is to find the count of nodes having their value in the range [L, R].
Examples:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.
Input: Tree in the image below, L = 4, R = 15
Output: 2
Explanation: The nodes in the given Tree that lies in the range [4, 15] are {5, 10}.Input: Tree in the image below, L = 8, R = 20
Output: 4
Approach: The given problem can be solved by performing any Tree Traversal and maintaining the count of nodes having their values in the range [L, R]. This article uses a DFS traversal.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Class for node of the Treeclass Node {public: int val; Node *left, *right;}; // Function to create a new Binary nodeNode* newNode(int item){ Node* temp = new Node(); temp->val = item; temp->left = temp->right = NULL; // Return the newly created node return temp;} // Function to find the count of// nodes in the given tree with// their value in the range [1, N]int countRange(Node* root, int low, int high, int count){ int val = 0; // If root exists if (root != NULL) { val += root->val >= low && root->val <= high ? 1 : 0; } // Otherwise return else { return 0; } // Add count of current node, // count in left subtree, and // count in the right subtree count = val + countRange(root->left, low, high, count) + countRange(root->right, low, high, count); // Return Answer return count;} // Driver Codeint main(){ Node* root = NULL; root = newNode(20); root->left = newNode(2); root->right = newNode(10); root->right->left = newNode(2); root->right->right = newNode(5); int L = 4, R = 15; cout << countRange(root, L, R, 0); return 0;} |
2
Time Complexity: O(N)
Auxiliary Space: O(1)



