0

I have written the code to implement binary search tree insertion and display the inorder notation of the tree. This code is not giving any output. Please help me. I think something might be wrong with the insert function where some of the insertions are not happening as expected. Also I am try to use a non recursive method to perform insertion.

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int val;
    struct node *lc, *rc;
};
struct node *getnode(int x)
{
    struct node *new = (struct node *)malloc(sizeof(struct node *));
    new->lc = NULL;
    new->rc = NULL;
    new->val = x;
    return new;
}

void inorder(struct node *root)
{
    if (root != NULL)
    {
        inorder(root->lc);
        printf("%d ", root->val);
        inorder(root->rc);
    }
}

void insert(struct node *root, int x)
{
    if (root == NULL)
    {
        struct node *new = getnode(x);
        root = new;
    }
    else
    {
        struct node *ptr1;
        struct node *ptr = root;
        while (ptr != NULL)
        {
            if (x < ptr->val)
            {
                ptr1 = ptr;
                ptr = ptr->lc;
            }
            else
            {
                if (x > ptr->val)
                {
                    ptr1 = ptr;
                    ptr = ptr->rc;
                }
            }
        }
        struct node *temp = getnode(x);
        if (ptr1->val > temp->val)
            ptr1->lc = temp;
        else
            ptr1->rc = temp;
    }
}
int main()
{
    struct node *root = NULL;
    insert(root, 75);
    insert(root, 85);
    insert(root, 25);
    insert(root, 12);
    insert(root, 13);
    insert(root, 15);
    insert(root, 100);
    insert(root, 105);
    printf("Inorder notation of tree is\n");
    inorder(root);
    return 0;
}

I was expecting the below as output. Inorder notation of tree is 12 13 15 25 75 85 100 105

  • Your `insert` method will not change the caller's `root` variable. `root` will remain NULL. – trincot Nov 12 '22 at 14:51
  • But i am passing a pointer isn't it supposed to modify the value of the passing argument – Aman Goswami Nov 12 '22 at 14:59
  • No, research call-by-value. The function has its own variable. Assigning to that local variable has no effect on the value that the caller passed. Only if the data *pointed-to* is modified will the caller see that modification. – trincot Nov 12 '22 at 15:02

0 Answers0