I am writing a function to insert a node in BST ,but getting segmentation fault.
/*
Node is defined as
typedef struct node
{
int data;
node * left;
node * right;
}node;
*/
node * findPos(node * tree, int value){
if(tree -> data > value){
return findPos(tree -> left, value);
}
else if (tree -> data < value){
return findPos(tree -> right, value);
}
return tree;
}
node * addNode(int value){
struct node * temp =(struct node *)malloc(sizeof(struct node));
temp->data = value;
temp->left = NULL;
temp -> right = NULL;
return temp;
}
node * insert(node * root, int value)
{
node * ptr = root;
if(ptr == NULL)
return addNode(value);
else if(ptr -> data > value){
ptr->left = findPos(ptr -> left, value);
}
else if(ptr -> data < value){
ptr->right = findPos(ptr -> right, value);
}
return root;
}
i am not able to understand which illegal memory i am trying to access which is giving this error. Please help me with this. Thanks in advance :)
There are two issues here:
insert should not recursively call findPos. Instead it should recursively call insert. Something like this (haven't tested it):
node * insert(node * root, int value) { node * ptr = root; if(ptr == NULL) return addNode(value); else if(ptr -> data > value) { return insert(ptr -> left, value); } else if(ptr -> data < value) { return insert(ptr -> right, value); } else return root; }
Thanks for the help guys!!! got the program working
/*
Node is defined as
typedef struct node
{
int data;
node * left;
node * right;
}node;
*/
node * addNode(int value){
struct node * temp =(struct node *)malloc(sizeof(struct node));
temp->data = value;
temp->left = NULL;
temp -> right = NULL;
return temp;
}
node * insert(node * root, int value)
{
node * ptr = root;
if(ptr == NULL)
return addNode(value);
else if(ptr -> data > value){
ptr->left = insert(ptr -> left, value);
}
else if(ptr -> data < value){
ptr->right = insert(ptr -> right, value);
}
return root;
}
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.