guys please debug it for coding Binary search tree

#include
using namespace std;

struct bstnode{

int data;
bstnode* left;
bstnode* right;

}

bstnode* getnewnode(int data){

bstnode* newnode = new bstnode();
newnode -> data=data;
newnode -> left = newnode->right = NULL;
return newnode;

}

bstnode* insert(bstnode* root,int data){

if(root == NULL){

root = getnewnode(data);
}

else if (data <= root->data ){

root->left= insert (root->left,data);

}
else{
root->right=insert(root->right,data);

}

return root;
}

bool search (bstnode* root,int data){

if(root==NULL)return false;
if(root->data = data)return true;
else if(data < root->data) return search(root->left,data);
    else return search(root->right,data);
}

int main()

{

bstnode* root =NULL;
root = insert (root,15);
root = insert(root,10);
root = insert(root,20);
root = insert(root,25);
root = insert(root,8);
root = insert(root,12);
int number;
cout<<"enter number be searched\n";
cin>>number;
if(search(root,number)==true)cout<<"Found\n";
else cout<< "Not Found\n";
return 0;

}

Mistakes:

-you missed a semicolon after your struct declaration:

struct bstnode{
int data;
bstnode* left;
bstnode* right;
}; // semicolon here

-Defnition of insert() function is wrong in the view that you do not seem to understand the type matching of parameters, the correct is:

     bstnode* insert(bstnode* root,int data){  
   // the function returns a pointer to the struct node, you missed this * in your code
    if(root==NULL){
    root = getnewnode(data);
    }
    else if (data <= root->data ){
        root->left= insert (root->left,data);
    } 
    else{ 
    	root->right=insert(root->right,data);
    }
    return root; 
    }

-In your search function the line,

if(root->data = data)return true; //
it should be if(root->data == data)return true;

For fully running code, see this.

No offense please, but can you yourself read the code above? :P. It’s tough for others to understand and find your bug. Please paste the proper indented code or give the ideone link. It makes the task easy for us to get the motive behind your logistics and coding.

1 Like