When i try to do like this:
int main(){
node * root;
insert(&root, 10);
insert(&root, 20);
insert(&root, 30);
insert(&root, 40);
insert(&root, 50);
insert(&root,60);
preorder(root);
return 0;
}
my code runs fine and gives output.
But when i do this:
int main(){
node * root;
insert(&root, 10);
insert(&root, 20);
insert(&root, 30);
insert(&root, 40);
insert(&root, 50);
insert(&root,60);
preorder(root);
node * t;
insert(&t,9);
insert(&t,15);
insert(&t,18);
insert(&t,33);
insert(&t,55);
insert(&t,44);
insert(&t,61);
return 0;
}
It gives a segmentation fault...
Also if i comment:
preorder(root);
the code just works fine..
If i do the preorder of node t at last it works fine... Don't know how i am getting this segmentation error when i try to print the preorder of root before t?
Code segment for insert:
void insert(node ** root, int d){
node * t= *root;
*root=_insert(t,d);
}
node * _insert(node * t, int d){
if(t==NULL)
return newNode(d);
else{
if(d < t->data)
t->left=_insert(t->left,d);
if(d > t->data)
t->right=_insert(t->right,d);
t->height= max(ht(t->left),ht(t->right))+1;
int bal= ht(t->left)-ht(t->right);
if(bal > 1 && d < t->data)
return rightRotate(t);
if(bal < -1 && d > t->data)
return leftRotate(t);
if(bal < -1 && d > t->data){
t->right=rightRotate(t->right);
return leftRotate(t);
}
if(bal >1 && d < t->data){
t->left=leftRotate(t->left);
return rightRotate(t);
}
return t;
}
}
Code segment of preorder:
void preorder(node * t){
if(t==NULL)
return;
else {
cout<<t->data<<" ";
preorder(t->left);
preorder(t->right);
}
}
Helper functions used in code and node structure:
struct node{
int data;
node * left;
node * right;
int height;
};
node * newNode(int d){
node * t;
t= new node;
t->data = d;
t->left=NULL;
t->right=NULL;
t->height=1;
return t;
}
int ht(node * t){
if(t==NULL)
return 0;
else
return t->height;
}
node * leftRotate(node * t){
node * y = t->right;
t->right= y->left;
y->left=t;
return y;
}
node * rightRotate(node * t){
node * y = t->left;
t->left= y->right;
y->right=t;
return y;
}
You have undefined behavior in your code, because local variables are not initialized, their values are indeterminate.
You need to initialize the variables before you try to use them, e.g.