I recently created a bst successfully in C..Then my attempt was to create an AVL..The first step in doing so .Was to add a extra component bf(balance factor ) in every node..I did it as follows.
struct tnode{
int info;
struct tnode*left;
struct tnode*right;
int bf;//new field for avl tree..
};
Everytime malloc assigns a address to new node while insertion...I assign its info part to the value entered by user..set the left and right pointer to NULL.In addition to this it assigns the bf of the newnode to 0..After insertion of first node(ie root node) program fails at the malloc part next time to even assign a memory to the newnode...As soon as I remove the part which says newnode->bf=0..The problem vanishes.. Why is this happening ?.Below is my main function and add() function which takes integer as input and insert it to tree with root node as 'root' declared globally.
int main(){
int choice,val;
deci:
printf("\n1.Insert");
printf("\n2.Display");
printf("\n3.Search.");
printf("\n4.Delete");
printf("\n5.Naa..");
scanf("%d",&choice);
switch(choice){
case 1:printf("\nEnter element to add:");
scanf("%d",&val);
add(val);
//display();
break;
case 2:display();
break;
case 3:printf("\nEnter element to search for:");
scanf("%d",&val);
search(val);
break;
case 4:printf("\nEnter element to Delete: ");
scanf("%d",&val);
deletei(val);
display();
break;
case 5:return 0;
}
goto deci;
return 0;
}
void add(int val){
struct tnode * newnode=(struct tnode * )malloc(sizeof(struct tnode *));
newnode->info=val;
newnode->left=newnode->right=NULL;
newnode->bf=0;//problem making,problem solved removing this statement
if(root==NULL){
root=newnode;
}
else{
struct tnode*tree=root;
struct tnode*ptree=NULL;
while(tree!=NULL){
if(val<tree->info){
ptree=tree;
tree=tree->left;
}
else{
ptree=tree;
tree=tree->right;
}
}
if(val<ptree->info){
ptree->left=newnode;
tree=ptree->left;
}
else{
ptree->right=newnode;
tree=ptree->right;
}
}
}