You are on page 1of 4

EXPT NO: 11 DATE: 08-10-2010 PROGRAM CODING:

REG. NO:31009205044

#include<stdio.h> #include<conio.h> #include<stdlib.h> typedef struct AVLnode { int element; struct AVLnode *left; struct AVLnode *right; int h; }*AVLTree; typedef AVLTree position; AVLTree root; int height(position p) { if(p==NULL) return -1; else return p->h; } position singleleft(position k2) { position k1; printf("\n Single rotation with left has been performed \n"); k1=k2->left; k2->left=k1->right; k1->right=k2; k2->h=max(height(k2->left),height(k2->right))+1; k1->h=max(height(k1->left),height(k1->right))+1; return k1; }

position singleright(position k1) { position k2; printf("\n Single rotation with right has been performed \n"); k2=k1->right; k1->right=k2->left; k2->left=k1; k1->h=max(height(k1->left),height(k1->right))+1; k2->h=max(height(k2->left),height(k2->right))+1; return k2; } position doubleleft(position k3) { k3->left=singleright(k3->left); return (singleleft(k3)); } position doubleright(position k1) { k1->right=singleleft(k1->right); return (singleright(k1)); } AVLTree insert(int x,AVLTree T) { if(T==NULL) { T=(AVLTree)malloc(sizeof(struct AVLnode)); T->element=x; T->left=T->right=NULL; T->h=0; } else if(x<T->element) { T->left=insert(x,T->left); if(height(T->left)-height(T->right)==2) { if(x<T->left->element) {

printf("\nImbalance occured in %d and %d is less than %d so \n",T>element,x,T->left->element); T=singleleft(T); } else { printf("\nImbalance occured in %d and %d is between than %d to %d so double rotation has to be performed...!!\n",T->element,x,T->element,T->left>element); T=doubleleft(T); } } } else if(x>T->element) { T->right=insert(x,T->right); if(height(T->left)-height(T->right)==-2) { if(x>T->right->element) { printf("\nImbalance occured in %d and %d is greater than %d so \n",T>element,x,T->right->element); T=singleright(T); } else { printf("\nImbalance occured in %d and %d is between than %d to %d so double rotation has to be performed...!!\n",T->element,x,T->element,T->right>element); T=doubleright(T); } } } T->h=max(height(T->left),height(T->right))+1; return T; } void print(AVLTree T) {

if(T) { print(T->left); printf("%d ",T->element); print(T->right); } } void main() { int ch, x,ans; root=NULL; clrscr(); do { printf("\n\n1. Insert an element \n2. Display Tree\nEnter your choice: "); scanf("%d",&ch); switch(ch) { case 1: printf("\nEnter the element: "); scanf("%d",&x); root=insert(x,root); break; case 2: printf("\nAVL Tree : "); if(root) { printf("\nThe root element is: %d",root->element); printf("\n"); } print(root); break; } printf("\n do you want to continue: \n1.yes\n2.no"); scanf("%d",&ans); }while(ans==1); getch(); }

You might also like