giving wrong answer. please help.
Print BST keys in given range
u have the build the bst in the order provided in the question and not by sorting the array
this is done by making the first element as root and following elements to be inserted to right if it is greater and left if it is lesser
that is also provided in the following code:
bstnode *insertinbst(bstnode *root, int data)
{
if(root==NULL)
{
return new bstnode(data);
}
if(data<=root->data)
{
root->left = insertinbst(root->left, data);
}
else
root->right = insertinbst(root->right, data);
return root;
}
bstnode *build()
{
int d;
cin>>d;
bstnode *root = NULL;
while(d!=-1)
{
root = insertinbst(root,d);
cin>>d;
}
return root;
}
in main()
{…
bstnode *root = build();
}
use this to build your bst
also print the nodes then in inorder traversal
void nodesinrangeinorder(node *root, int k1, int k2){
if ( NULL == root )
return;
if ( k1 < root->data )
nodesinrangeinorder(root->left, k1, k2); //recur for left subtree only if root->data is greater than lower limit since all the elements on the left are smaller
if ( k1 <= root->data && k2 >= root->data )
cout<data<<" "; //print root->data if it is in range
if ( k2 > root->data )
nodesinrangeinorder(root->right, k1, k2); //similar logic as case 1
}
if your doubt is solved, kindly mark it as resolved