What's wrong in my code? Why is it printing incorrect preorder traversal?

#include
#include
using namespace std;
class node{
public:
int data;
node* left;
node* right;
node(int d){
data=d;
left=NULL;
right=NULL;
}
};
node* build_tree_from_array(int arr[],int s,int e)
{
if(s>e){
return NULL;
}
int mid=(s+e)/2;
node* root=new node(arr[mid]);
root->left=build_tree_from_array(arr,s,mid-1);
root->right=build_tree_from_array(arr,mid+1,e);
return root;
}
void preorder(node* root){
if(root==NULL){
return;
}
cout<data<<" ";
preorder(root->left);
preorder(root->right);
return;
}
void PrintRange(node* root,int a,int b){

if(root==NULL){
    return;
}

PrintRange(root->left,a,b);
if(root->data<=b and root->data>=a){
    cout<<root->data<<" ";
}
PrintRange(root->right,a,b);
return;

}
int main() {
int t;
cin>>t;
while(t–){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
sort(arr,arr+n);
node* root=build_tree_from_array(arr,0,n-1);
int b,c;
cin>>b>>c;

    cout<<"# Preorder : ";
    preorder(root);        
    cout<<endl<<"# Nodes within range are : ";
    PrintRange(root,b,c);
    cout<<endl;
}
return 0;

}#include
#include
using namespace std;
class node{
public:
int data;
node* left;
node* right;
node(int d){
data=d;
left=NULL;
right=NULL;
}
};
node* build_tree_from_array(int arr[],int s,int e)
{
if(s>e){
return NULL;
}
int mid=(s+e)/2;
node* root=new node(arr[mid]);
root->left=build_tree_from_array(arr,s,mid-1);
root->right=build_tree_from_array(arr,mid+1,e);
return root;
}
void preorder(node* root){
if(root==NULL){
return;
}
cout<data<<" ";
preorder(root->left);
preorder(root->right);
return;
}
void PrintRange(node* root,int a,int b){

if(root==NULL){
    return;
}

PrintRange(root->left,a,b);
if(root->data<=b and root->data>=a){
    cout<<root->data<<" ";
}
PrintRange(root->right,a,b);
return;

}
int main() {
int t;
cin>>t;
while(t–){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
sort(arr,arr+n);
node* root=build_tree_from_array(arr,0,n-1);
int b,c;
cin>>b>>c;

    cout<<"# Preorder : ";
    preorder(root);        
    cout<<endl<<"# Nodes within range are : ";
    PrintRange(root,b,c);
    cout<<endl;
}
return 0;

}

hi @akshat_bharani
kindly save ur code on coding blocks ide and send link…
or u can refer my code -->

code link: https://ide.codingblocks.com/s/644747

hi @akshat_bharani

sort(arr,arr+n);

u are sorting all the nodes before that’s why ur code is giving incorrect o/p… just build the tree in order of nodes given… then compute the ans… refer my code i sent above…

Okay sure got it. Thanks!!

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.