I have a code for AVL tree here:
#include<iostream>
#include<cstdlib>
using namespace std;
typedef struct avl {
avl *left;
avl* right;
avl* parent;
int data;
} avl;
class AVL{
avl* root;
public:
void insert(int d);
void inorder(avl*);
void preorder();
void rr_rotation(avl*);
void ll_rotation(avl*, int);
void rl_rotation(avl*);
void lr_rotation(avl*);
int height(avl *t);
int getbalance(avl *parent);
void check_avl(avl*);
avl* getroot();
AVL(){
root=NULL;
}
};
avl* AVL::getroot(){
return root;
}
int AVL::height(avl *p){
int l_height=0, r_height=0;
int h=0;
if(p!=nullptr){
l_height=height(p->left);
r_height=height(p->right);
h= l_height>r_height ? l_height : r_height;
}
return ++h;
}
int AVL::getbalance(avl *p){
int l_height=0, r_height=0;
if(p!=nullptr){
l_height=height(p->left);
r_height=height(p->right);
}
int b= l_height-r_height;
return b;
}
void AVL:: rr_rotation(avl *tree){
cout<<"RR rotation"<<endl;
avl* t=tree->left;
t->right=tree;
if(root==tree)
root=t;
else{
tree=t;
}
}
void AVL:: ll_rotation(avl *tree, int l=0){
cout<<"LL rotation"<<endl;
avl* t=tree->right;
t->left=tree;
if(root==tree)
root=t;
else{
tree=t;
}
}
void AVL:: lr_rotation(avl *tree){
cout<<"LR rotation"<<endl;
ll_rotation(tree->left,1);
rr_rotation(tree);
}
void AVL:: rl_rotation(avl *tree){
cout<<"RL rotation"<<endl;
rr_rotation(tree->right);
ll_rotation(tree);
}
void AVL::insert(int d){
cout<<"Inserting "<<d<<endl;
int c=0;
avl *t = (avl*)malloc(sizeof(avl));
t->data=d;
//cout<<t->data;
t->parent=t->left=t->right=NULL;
if(root==NULL){
root=t;
}
else{
avl* tree;
avl* sample;
tree=root;
while(tree!=NULL){
if(d<tree->data){
sample=tree;
tree=tree->left;
c=1;
}
else{
sample=tree;
tree=tree->right;
c=2;
}
}
switch(c){
case 1:
sample->left=t;
(sample->left)->parent=sample;
break;
case 2:
sample->right=t;
t->parent=sample;
}
}
check_avl(root);
}
void AVL::check_avl(avl * t){
if(t!=NULL){
int balance=getbalance(t);
if(balance>1){
avl* child=t->left;
if((child!=NULL) && (child->left!=NULL))
rr_rotation(t);
else if((child!=NULL) && (child->right!=NULL))
lr_rotation(t);
}
else if(balance<-1){
avl* child=t->right;
if((child!=NULL) && (child->left!=NULL))
rl_rotation(t);
else if((child!=NULL) && (child->right!=NULL))
ll_rotation(t);
}
check_avl(t->left);
check_avl(t->right);
}
}
void AVL::inorder(avl* t){
if(t!=NULL){
inorder(t->left);
cout<<t->data<<" ";
inorder(t->right);
}
}
int main()
{
AVL a;
a.insert(10);
a.insert(6);
a.insert(3);
a.insert(20);
a.insert(15);
a.insert(8);
a.insert(5);
a.insert(9);
a.inorder(a.getroot());
}
When I'm trying to insert 3, I'm getting a segmentation fault.
Help to figure out my issue