whats the problem with this code

struct node
{
int data;
node *left,*right;
} ;

void add(node *root,int val)
{
	node *temp=new node;
	if(root=NULL)
	{
	temp->data=val;
	temp->left=temp->right=NULL;
	root=temp;
	return;
	}
	else if(val<root->data)
		add(root->left,val);
	else if(val>root->data)
		add(root->right,val);
}

void inorder(node *root)
{
	if(root!=NULL)
	{
		inorder(root->left);
		cout<<root->data;
		inorder(root->right);
	}
}

In the function ADD, see the if condition, it should be if(root==NULL) not if(root=NULL) it will make root null every time you use ADD :stuck_out_tongue:

EIDT : no, the inorder function is perfect, your add function is flawed

Just wrote out this non-recursive add function(which I would prefer), read it and try to find out whats wrong with your implementation

struct node
{
    int data;
    node *left,*right;
}*root=NULL;

void add(node* root,int val)
{   
    node *x=root;
    node *y=NULL;
    while(x!=NULL)
    {
        y=x;
        if(val<x->data)
            x=x->left;
        else
            x=x->right;
    }
    node* temp;
    temp=new node;
    temp->data=val;
    temp->left=temp->right=NULL;
    
    if(y==NULL)
        root=temp;
    else if(val<y->data)
        y->left=temp;
    else
        y->right=temp;
}

void inorder(node *x)
{
    if(x!=NULL)
    {
        inorder(x->left);
        cout<<x->data<<" ";
        inorder(x->right);
    }
}
1 Like

still not working.
problem is in inorder