I tried writing a tree program in C, starting with the insert function as shown below:
void insert(int val)
{
    struct node * nn = (struct node *)malloc(sizeof(struct node));
    nn->data = val;
    nn->left = NULL;
    nn->right = NULL;
    if(root == NULL)
    {
        root = nn;
    }
    else
    {
        struct node *ptr = root;
        while(ptr->left != NULL && ptr->right != NULL)
        {
            if(nn->data < ptr->data)
            {
                ptr = ptr->left;
            }
            else
            {
                ptr = ptr->right;
            }
        }
        if(ptr->data < nn->data)
        {
            ptr->right = nn;
        }
        else
        {
            ptr->left = nn;
        }
}
Then I wrote the code for displaying the nodes of the tree so formed:
void display()
{
    struct node *n;
    
    if(root == NULL)
    {
        printf("Tree is Empty\n");
    }
    else
    {
        n = root;
        
        if(n!=NULL)
        {
            printf("%d",n->data);
            display(n->left);
            display(n->right);
        }    
    }
}
This is the main function:
int main()
{
    int ch,val;
    while(ch!=3)
    {
        printf("1. Insert\n2. Display\n3. Exit\nEnter your choice: ");
        scanf("%d",&ch);
        switch(ch)
        {
            case 1:
            printf("Enter value to be inserted: ");
            scanf("%d",&val);
            insert(val);
            break;
            case 2:
            display();
            break;
            case 3:
            ch=3;
            printf("Exiting....\n");
            break;
            default:
            printf("Invalid choice, please try again\n");
            break;
        }
    }
    return 0;
}
But when I tried executing the display function after inserting a few nodes, it only printed the first node in an infinite loop.
Could someone please help me get around this problem?
 
     
    