Search code examples
searchtreeinsertbinarytraversal

why such an annoying binary search tree(bst) seg.fault error?


input no. of elements , elements of binary search tree , input elemt whoose subtree you want to display

#include <stdio.h>

defn of struct node of bst

typedef struct node
{
int info;
struct node *right, *left;
}NODE; 

insert fn , node at leaf

struct node* insertBst(struct node* root, int ele)
{

if(root == NULL)
{
    NODE* temp = (NODE*)malloc(sizeof(NODE));
    temp -> info = ele;
    temp -> right = temp -> left = NULL;
    return root;
}

else if(ele > root -> info)
{
    root -> right = insertBst(root -> right, ele);
}

else if(ele < root -> info)
{
    root -> left = insertBst(root -> left, ele);
}


}

searching for the address of the ele

NODE* search(int ele, NODE* root)
{
if( root == NULL) return NULL;
if(ele > root -> info)
{
    return search(ele, root -> right); 
}

else if( ele < root -> info)
{
    return search(ele, root -> left);
}

else if(ele == root -> info) //ele found
{
    return root;
}

 }

displaying the made bst using pre order : ROOT , LEFT, RIGHT

void preorder(NODE* root)
{
   if(root)
{
    printf("%d ", root -> info);
    preorder(root -> left);
    preorder(root -> right);
 }
}

driver where i call insert to create my bst, node whose subtree im >>displaying

int main()
{
int n, ele; //no. of elements in bst
NODE* root = NULL;
printf("no. of bst elements");
scanf("%d", &n);
printf("elements to be inserted in bst");
for(int i = 0; i < n; ++i)
{
    scanf("%d", &ele);
    NODE* t = insertBst(root, ele);
}

printf("element whose subtree needs to be displayed");
scanf("%d", ele); //elements whose subtree is to be diplayed
NODE *temp;
temp = search(ele, root);
preorder(temp);
}

Solution

  • Probably the segfault is in the line:

    scanf("%d", ele);

    Where you should have passed the address of ele instead of it's value, like you did inside the for loop.

    Also, your program won't work because function insertBst will never assign a root node as any time if(root == NULL) is true (always) you will allocate a node as you should, but you returns the same root which is still NULL. You probably meant to return temp.

    Also, it's good practice to check temp (after the malloc) for NULL pointer before dereferencing it, as malloc can fail and return NULL, and dereferencing it will crash your program.