Home > Net >  i got the error When i printing the inorder traversing in my C code which is given below
i got the error When i printing the inorder traversing in my C code which is given below

Time:12-29

When i print Binary Search Tree nodes in Inorder Traversal: it only prints 1st element. it takes the input from user and prints the user input but it does not print inorder traversing Also please explain me execution of for loop part.

  1. Can we do this code in another way? Also how we can perform deletion operation?
#include<conio.h>
#include<stdlib.h>

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


void inorder(struct node *root)
{
    if(root)
    {
        inorder(root->left);
        printf("  %d",root->data);
        inorder(root->right);
    }
}

int main()
{
    int n , i;
    struct node *p , *q , *root;
    printf("Enter the number of nodes to be insert: ");
    scanf("%d",&n);

    printf("\nPlease enter the numbers to be insert: ");

    for(i=0;i<i  )
    {
        p = (struct node*)malloc(sizeof(struct node));
        scanf("%d",&p->data);
        p->left = NULL;
        p->right = NULL;
        if(i == 0)
        {
            root = p; // root always point to the root node
        }
        else
        {
            q = root;   // q is used to traverse the tree
            while(1)
            {
                if(p->data > q->data)
                {
                    if(q->right == NULL)
                        {
                        q->right = p;
                        break;
                        }
                    else
                        q = q->right;
                }
                else
                {
                    if(q->left == NULL)
                        {
                        q->left = p;
                        break;
                        }
                    else
                        q = q->left;
                }
            }

        }

    }

printf("\nBinary Search Tree nodes in Inorder Traversal: ");
inorder(root);
printf("\n");

return 0;
}

CodePudding user response:

Most likely the cause of the problem is this condition:

for(i=0;i<i  )

i<i causes undefained behaviour, because you read and write i without a sequence point in between. It's also logically wrong, because you don't use n at all. I think you wanted this instead:

//         VVV
for(i=0; i < n; i  )
  •  Tags:  
  • c
  • Related