Here is my code for the creation and insertion of the binary search tree
struct BTNode
{
int info;
struct BTNode *left, *right;
};
struct BTNode* create(int data)
{
struct BTNode *root;
struct BTNode *n = malloc(sizeof(struct BTNode));
n->info = data;
n->left = NULL;
n->right = NULL;
root = n;
return(root);
}
struct BTNode* insert(struct BTNode *root, int data)
{
struct BTNode *ptr;
struct BTNode *n = malloc(sizeof(struct BTNode));
if (n == NULL)
printf("\nOUT OF MEMORY!\n");
n->info = data;
n->left = NULL;
n->right = NULL;
ptr = root;
while (ptr != NULL){
if (data < ptr->info){
if (ptr->left == NULL)
ptr->left = n;
ptr = ptr->left;
}
else if (data > ptr->info){
if (ptr->right == NULL)
ptr->right = n;
ptr = ptr->right;
}
}
return(n);
}
and here is the main() function
int main()
{
struct BTNode *root = NULL;
int choice, data;
printf("\nWrite the root data: ");
scanf("%d", &data);
root = create(data);
while (1){
printf("\n1.Insert 2.Preorder 3.Exit\n");
scanf("%d", &choice);
switch(choice){
case 1:
printf("\nWrite the data: ");
scanf("%d", &data);
insert(root, data);
break;
I am able to create the root node but whenever I am trying to insert the data, I give my data and the compiler stops doing anything. Any idea why this is happening?
Your while()
loop goes on forever because you keep going even after you find a place to insert the node:
while(ptr!=NULL){
if(data<ptr->info){
if(ptr->left==NULL)
ptr->left=n;
ptr=ptr->left;
}
else if(data>ptr->info){
if(ptr->right==NULL)
ptr->right=n;
ptr=ptr->right;
}
}
You need to break out of the while()
loop after inserting the node:
while (ptr != NULL) {
if (data < ptr->info) {
if (ptr->left == NULL) {
ptr->left = n;
break;
}
ptr = ptr->left;
} else if (data > ptr->info) {
if (ptr->right == NULL) {
ptr->right = n;
break;
}
ptr = ptr->right;
}
}
Also, bonus points for checking if malloc()
fails
struct BTNode *n = malloc(sizeof(struct BTNode));
if (n == NULL)
printf("\nOUT OF MEMORY!\n");
But negative points for simply continuing on anyway, you should exit the function if malloc()
fails
struct BTNode *n = malloc(sizeof(struct BTNode));
if (n == NULL) {
printf("\nOUT OF MEMORY!\n");
return NULL:
}
And then of course, the code calling insert()
should know what to do if insert()
returns NULL.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.