1

When I try to run my program, it takes input till 2 or 3 steps and then it ends abruptly, even if I press Y for entering more elements.This is the screenshot of my output: enter image description here Here's my segment of code, lc stands for left child, rc stands for right child and ht stands for height of tree:

void inorder(struct node *root) //print inorder
{
    if(root->lc!=NULL)
        inorder(root->lc);
    printf("%d ",root->data);
    if(root->rc!=NULL)
        inorder(root->rc);
}
struct node *insert(struct node *T,int x) //code for insertion of a node
{
    if(T==NULL)
    {
        T=(struct node*)malloc(sizeof(struct node));
        T->data=x;
        T->lc=NULL;
        T->rc=NULL;
    }
    else
    {
        if(x > T->data)        
        {
            T->rc=insert(T->rc,x);
            if(BF(T)==-2)
                if(x>T->rc->data)
                    T=RR(T);
                else
                    T=RL(T);
        }
        else
        {
            if(x<T->data)
            {
                T->lc=insert(T->lc,x);
                if(BF(T)==2)
                    if(x < T->lc->data)
                        T=LL(T);
                    else
                        T=LR(T);
            }
        }
        T->ht=height(T);
        return(T);
    }
}

int main()
{
    struct node *root=NULL;
    int ele;
    char ch;
    do
    {
        printf("\n Enter the value to be inserted in AVL: ");
        scanf("%d",&ele);
        root=insert(root,ele);
        printf("\n Want to insert more elements? (y/n): ");
        getchar();
        scanf("%c",&ch);
    }while(ch=='y' || ch=='Y');
    printf("\n Press any key to print inorder traversal: ");
    getchar();
    inorder(root);
    return 0;
}
ankastic
  • 171
  • 2
  • 14
  • 2
    The line `return(T);` in `insert` function is in wrong place, it should be one level up, now in case where `T==NULL` your function doesn't return any value, it leads to undefined behaviour. – rafix07 Oct 09 '18 at 18:41
  • Got it. Thanks. :) – ankastic Oct 09 '18 at 19:09

0 Answers0