I am trying to implement the BST in iterative method using c programming. Inserting only one element will not cause segmentation error(2nd line in main function root = insert(root,50). But adding more than one element in BST shows segmentation error. I don't know where the mistake. The code is as follows:
#include <stdio.h>
#include <stdlib.h>
struct bstnode
{
int data;
struct bstnode *left;
struct bstnode *right;
};
struct bstnode* getnode(int data)
{
struct bstnode *temp = malloc(sizeof(struct bstnode));
if(temp == NULL)
{
printf("failed");
}
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
struct bstnode* insert(struct bstnode *root,int data)
{
if(root == NULL)
{
root = getnode(data);
return root;
}
struct bstnode *temp = root;
struct bstnode *parent;
int flag;
while(temp != NULL)
{
parent = temp;
if(data < temp->data)
{
temp = temp->left;
flag = 1;
}
if(data > temp->data)
{
temp = temp->right;
flag = 0;
}
}
if(flag == 1)
{
parent->left = getnode(data);
}
else
parent->right = getnode(data);
return root;
}
void inorder(struct bstnode* root)
{
if (root != NULL) {
inorder(root->left);
printf("%d \n", root->data);
inorder(root->right);
}
}
int main() {
struct bstnode *root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
inorder(root);
return 0;
}
CodePudding user response:
Think what happens here when data
is less than temp->data
and temp->left
is NULL
?
if(data < temp->data)
{
temp = temp->left;
flag = 1;
}
if(data > temp->data)
{
temp = temp->right;
flag = 0;
}
You probably want to do an else if
instead of just if
in this case.
Also what happens if data
is equal to temp->data
?