I have written C code as an assignment for AVL tree. It runs fine on Turbo c++, but it fails on pelles c (32 bit ) for some examples.
tried this: 36 5 77 1 61 11 59 15 48 19
or you can try : 1 2 3 4
thanks in advance !
#include<stdlib.h>
#include<conio.h>
#include<stdio.h>
typedef struct avlnode
{
int data;
struct avlnode *left,*right;
}node;
int maximum(int num_1,int num_2)
{
if(num_1>num_2)
return(num_1);
return(num_2);
}
int height(node *head)
{
if (head == NULL)
return 0;
else
return (maximum(height(head->left), height(head->right)) + 1);
}
void preorder(node *head)
{
if (head != NULL)
{
printf(" %d", head->data);
preorder(head->left);
preorder(head->right);
}
}
node * LL(node * head)
{
node *temp;
temp=head->left;
head->left=temp->right;
temp->right=head;
return temp;
}
node * RR(node * head)
{
node *temp;
temp=head->right;
head->right=temp->left;
temp->left=head;
return temp;
}
node * LR(node * head)
{
head->left=LL(head->left);
head=RR(head);
return head;
}
node * RL(node * head)
{
head->right=LL(head->right);
head=RR(head);
return head;
}
node * insert(node * head,int ele)
{
if(head==NULL)
{
head=(node *)malloc(sizeof(node));
head->data=ele;
head->left=head->right=NULL;
}
else
{
if(ele<head->data)
{
head->left=insert(head->left,ele);
if( abs( height(head->left)-height(head->right))==2)
{
if(ele<head->left->data)
head=LL(head);
else
head=LR(head);
}
}
else
{
head->right=insert(head->right,ele);
if( abs( height(head->left)-height(head->right))==2)
{
if(ele<head->left->data)
head=RL(head);
else
head=RR(head);
}
}
}
return head;
}
int main()
{
int ch,ele;
node *head=NULL;
while(9)
{
printf("\n\n1:Insert 2:Display 3:Exit ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\n\nEnter element to insert : ");
scanf("%d",&ele);
head=insert(head,ele);
break;
case 2:
printf("\n\nPreorder traversal is : \n\n");
preorder(head);
break;
case 3:
return 0;
}
}
return 0;
}