My test cases are passing but unable to understand where I am doing wrong as its giving wrong answer.
Here’s my code:
#include
#include <stdio.h>
using namespace std;
class node
{
public:
int data;
node* left = NULL;
node* right = NULL;
node(int data)
{
this->data = data;
left = NULL;
right = NULL;
}
};
node* InsertInBST(node* root , int d)
{
if(root == NULL)
{
root = new node(d);
return root;
}
if(root->data < d)
{
root->right = InsertInBST(root->right,d);
}
if(d <= root->data)
{
root->left = InsertInBST(root->left,d);
}
return root;
}
node* BuildBST()
{
int size;
cin>>size;
node* root = NULL;
for(int i=0; i<size; i ++)
{
int d;
scanf("%d ",&d);
root = InsertInBST(root,d);
}
return root;
}
void printPreOrder(node* root)
{
if(root==NULL)
{
return;
}
cout<<root->data<<" ";
printPreOrder(root->left);
printPreOrder(root->right);
}
void NodesWithinRange(node* root, int a, int b)
{
if( root == NULL)
{
return;
}
if(root->data > a)
{
NodesWithinRange(root->left,a,b);
}
if(root->data >=a || root->data <=b)
{
cout<data<<" ";
}
if(root->data < b)
{
NodesWithinRange(root->right,a,b);
}
}
int main() {
int t;
cin>>t;
while(t>0)
{
node* root = BuildBST();
cout<<"Preorder : ";
printPreOrder(root);
cout<<endl;
cout<<"Nodes within range are : ";
int a,b;
cin>>a>>b;
NodesWithinRange(root,a,b);
cout<<endl;
t–;
}
return 0;
}
Please check it once.
TIA !!