[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.
C++
// C++ program to count BST nodes within // a given range#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Returns count of nodes in BST in range [l, h]intgetCount(Node*root,intl,inth){// Base caseif(root==nullptr)return0;// If current node is in range, then // include it in count and recur for // left and right children of itif(root->data<=h&&root->data>=l)return1+getCount(root->left,l,h)+getCount(root->right,l,h);// If current node is smaller than low, // then recur for right childelseif(root->data<l)returngetCount(root->right,l,h);// Else recur for left childelsereturngetCount(root->left,l,h);}intmain(){// Create a hard coded bst.// 10// / \ // 5 50 // / / \ // 1 40 100Node*root=newNode(10);root->left=newNode(5);root->right=newNode(50);root->left->left=newNode(1);root->right->left=newNode(40);root->right->right=newNode(100);intl=5;inth=45;cout<<getCount(root,l,h)<<endl;return0;}
C
// C program to count BST nodes // within a given range#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*left;structNode*right;};// Returns count of nodes in BST in range [l, h]intgetCount(structNode*root,intl,inth){// Base caseif(root==NULL)return0;// If current node is in range, then// include it in count and recur for// left and right children of itif(root->data<=h&&root->data>=l)return1+getCount(root->left,l,h)+getCount(root->right,l,h);// If current node is smaller than low,// then recur for right childelseif(root->data<l)returngetCount(root->right,l,h);// Else recur for left childelsereturngetCount(root->left,l,h);}structNode*createNode(intx){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=x;newNode->left=NULL;newNode->right=NULL;returnnewNode;}intmain(){// Create a hard coded bst.// 10// / \ // 5 50// / / \ // 1 40 100structNode*root=createNode(10);root->left=createNode(5);root->right=createNode(50);root->left->left=createNode(1);root->right->left=createNode(40);root->right->right=createNode(100);intl=5;inth=45;printf("%d\n",getCount(root,l,h));return0;}
Java
// Java program to count BST nodes// within a given rangeimportjava.util.ArrayList;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Returns count of nodes in BST in range [l, h]staticintgetCount(Noderoot,intl,inth){// Base caseif(root==null)return0;// If current node is in range, // include it and recur for left and rightif(root.data<=h&&root.data>=l)return1+getCount(root.left,l,h)+getCount(root.right,l,h);// If current node is smaller // than low, recur for right childelseif(root.data<l)returngetCount(root.right,l,h);// Else recur for left childelsereturngetCount(root.left,l,h);}publicstaticvoidmain(String[]args){// Create a hard coded bst.// 10// / \// 5 50// / / \// 1 40 100Noderoot=newNode(10);root.left=newNode(5);root.right=newNode(50);root.left.left=newNode(1);root.right.left=newNode(40);root.right.right=newNode(100);intl=5;inth=45;System.out.println(getCount(root,l,h));}}
Python
# Python program to count BST nodes within # a given rangeclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=NonedefgetCount(root,l,h):# Base caseifrootisNone:return0# If current node is in range, # include it and recur for left and rightifroot.data<=handroot.data>=l:return1+getCount(root.left,l,h) \
+getCount(root.right,l,h)# If current node is smaller # than low, recur for right childelifroot.data<l:returngetCount(root.right,l,h)# Else recur for left childelse:returngetCount(root.left,l,h)if__name__=="__main__":# Create a hard coded bst.# 10# / \# 5 50# / / \# 1 40 100root=Node(10)root.left=Node(5)root.right=Node(50)root.left.left=Node(1)root.right.left=Node(40)root.right.right=Node(100)l=5h=45print(getCount(root,l,h))
C#
// C# program to count BST nodes within // a given rangeusingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Returns count of nodes in BST in range [l, h]staticintgetCount(Noderoot,intl,inth){// Base caseif(root==null)return0;// If current node is in range, // include it and recur for left and rightif(root.data<=h&&root.data>=l)return1+getCount(root.left,l,h)+getCount(root.right,l,h);// If current node is smaller // than low, recur for right childelseif(root.data<l)returngetCount(root.right,l,h);// Else recur for left childelsereturngetCount(root.left,l,h);}staticvoidMain(string[]args){// Create a hard coded bst.// 10// / \// 5 50// / / \// 1 40 100Noderoot=newNode(10);root.left=newNode(5);root.right=newNode(50);root.left.left=newNode(1);root.right.left=newNode(40);root.right.right=newNode(100);intl=5;inth=45;Console.WriteLine(getCount(root,l,h));}}
JavaScript
// JavaScript program to count BST nodes// within a given rangeclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Returns count of nodes in BST in range [l, h]functiongetCount(root,l,h){// Base caseif(root===null)return0;// If current node is in range, include// it and recur for left and rightif(root.data<=h&&root.data>=l)return1+getCount(root.left,l,h)+getCount(root.right,l,h);// If current node is smaller than // low, recur for right childelseif(root.data<l)returngetCount(root.right,l,h);// Else recur for left childelsereturngetCount(root.left,l,h);}// Create a hard coded bst.// 10// / \// 5 50// / / \// 1 40 100letroot=newNode(10);root.left=newNode(5);root.right=newNode(50);root.left.left=newNode(1);root.right.left=newNode(40);root.right.right=newNode(100);letl=5;leth=45;console.log(getCount(root,l,h));
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:
C++
// C++ program to count BST nodes within a// given range#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Returns count of nodes in BST in range [l, h]intgetCount(Node*root,intl,inth){// Base caseif(root==nullptr)return0;queue<Node*>q;q.push(root);intans=0;while(!q.empty()){Node*curr=q.front();q.pop();// If current node is in range, then // increment the count and push the // left and right children into queue.if(curr->data<=h&&curr->data>=l){ans++;if(curr->left!=nullptr)q.push(curr->left);if(curr->right!=nullptr)q.push(curr->right);}// If current node is smaller than low, // then push right child into queue.elseif(curr->data<l){if(curr->right!=nullptr)q.push(curr->right);}// Else push left childelse{if(curr->left!=nullptr)q.push(curr->left);}}returnans;}intmain(){// Create a hard coded bst.// 10// / \ // 5 50 // / / \ // 1 40 100Node*root=newNode(10);root->left=newNode(5);root->right=newNode(50);root->left->left=newNode(1);root->right->left=newNode(40);root->right->right=newNode(100);intl=5;inth=45;cout<<getCount(root,l,h)<<endl;return0;}
Java
// Java program to count BST nodes // within a given rangeimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Returns count of nodes in BST in range [l, h]staticintgetCount(Noderoot,intl,inth){// Base caseif(root==null)return0;Queue<Node>q=newLinkedList<>();q.add(root);intans=0;while(!q.isEmpty()){Nodecurr=q.poll();// If current node is in range, then // increment the count and push the // left and right children into queue.if(curr.data<=h&&curr.data>=l){ans++;if(curr.left!=null)q.add(curr.left);if(curr.right!=null)q.add(curr.right);}// If current node is smaller than low, // then push right child into queue.elseif(curr.data<l){if(curr.right!=null)q.add(curr.right);}// Else push left childelse{if(curr.left!=null)q.add(curr.left);}}returnans;}publicstaticvoidmain(String[]args){// Create a hard coded bst.// 10// / \// 5 50 // / / \ // 1 40 100Noderoot=newNode(10);root.left=newNode(5);root.right=newNode(50);root.left.left=newNode(1);root.right.left=newNode(40);root.right.right=newNode(100);intl=5;inth=45;System.out.println(getCount(root,l,h));}}
Python
# Python Program to count BST nodes # within a given rangefromcollectionsimportdequeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Returns count of nodes in BST in# range [l, h]defgetCount(root,l,h):# Base caseifrootisNone:return0q=deque([root])ans=0whileq:curr=q.popleft()# If current node is in range, then # increment the count and push the # left and right children into queue.ifl<=curr.data<=h:ans+=1ifcurr.leftisnotNone:q.append(curr.left)ifcurr.rightisnotNone:q.append(curr.right)# If current node is smaller than low, # then push right child into queue.elifcurr.data<l:ifcurr.rightisnotNone:q.append(curr.right)# Else push left childelse:ifcurr.leftisnotNone:q.append(curr.left)returnansif__name__=='__main__':# Create a hard coded bst.# 10# / \# 5 50 # / / \ # 1 40 100root=Node(10)root.left=Node(5)root.right=Node(50)root.left.left=Node(1)root.right.left=Node(40)root.right.right=Node(100)l=5h=45print(getCount(root,l,h))
C#
// C# Program to count BST nodes within// a given rangeusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Returns count of nodes in BST in range [l, h]staticintGetCount(Noderoot,intl,inth){// Base caseif(root==null)return0;Queue<Node>q=newQueue<Node>();q.Enqueue(root);intans=0;while(q.Count>0){Nodecurr=q.Dequeue();// If current node is in range, then // increment the count and push the // left and right children into queue.if(curr.data>=l&&curr.data<=h){ans++;if(curr.left!=null)q.Enqueue(curr.left);if(curr.right!=null)q.Enqueue(curr.right);}// If current node is smaller than low, // then push right child into queue.elseif(curr.data<l){if(curr.right!=null)q.Enqueue(curr.right);}// Else push left childelse{if(curr.left!=null)q.Enqueue(curr.left);}}returnans;}staticvoidMain(string[]args){// Create a hard coded bst.// 10// / \// 5 50 // / / \ // 1 40 100Noderoot=newNode(10);root.left=newNode(5);root.right=newNode(50);root.left.left=newNode(1);root.right.left=newNode(40);root.right.right=newNode(100);intl=5;inth=45;Console.WriteLine(GetCount(root,l,h));}}
JavaScript
// JavaScript Program to count BST nodes// within a given rangeclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Returns count of nodes in BST in range [l, h]functiongetCount(root,l,h){// Base caseif(root===null)return0;letq=[];q.push(root);letans=0;while(q.length>0){letcurr=q.shift();// If current node is in range, then // increment the count and push the // left and right children into queue.if(curr.data>=l&&curr.data<=h){ans++;if(curr.left!==null)q.push(curr.left);if(curr.right!==null)q.push(curr.right);}// If current node is smaller than low, // then push right child into queue.elseif(curr.data<l){if(curr.right!==null)q.push(curr.right);}// Else push left childelse{if(curr.left!==null)q.push(curr.left);}}returnans;}// Create a hard coded bst.// 10// / \// 5 50 // / / \ // 1 40 100letroot=newNode(10);root.left=newNode(5);root.right=newNode(50);root.left.left=newNode(1);root.right.left=newNode(40);root.right.right=newNode(100);letl=5;leth=45;console.log(getCount(root,l,h));