Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I need help for binary search algorithm in C programming

#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node *left;
    struct node *right;
};

struct node * add(struct node * root,int newData){
    if (root==NULL)
    {
        struct node * root = (struct node *)malloc(sizeof(struct node));
        root->data=newData;
        root->left=NULL;
        root->right=NULL;
        return root;
    }
    
    struct node * tmp = root;
    if (tmp->data<newData)
        tmp->right = add(tmp->right,newData);
    if (tmp->data >newData)
        tmp->left = add(tmp->left,newData);
}



void pre_order_traversal(struct node* root) {
    if (root==NULL)
        return;
    if(root != NULL) {
      printf("%d ",root->data);
      pre_order_traversal(root->left);
      pre_order_traversal(root->right);
   }
}

void inorder_traversal(struct node* root) {
    if (root==NULL)
        return;
   if(root != NULL) {
      inorder_traversal(root->left);
      printf("%d ",root->data);          
      inorder_traversal(root->right);
   }
}

void post_order_traversal(struct node* root) {
    if (root==NULL)
        return;
   if(root != NULL) {
      post_order_traversal(root->left);
      post_order_traversal(root->right);
      printf("%d ", root->data);
   }
}

int main(){
    struct node * tree1 = NULL;
    tree1 = add(tree1,5);
    tree1 = add(tree1,17);
    tree1 = add(tree1,21);
    tree1 = add(tree1,19);
    

    pre_order_traversal(tree1);
}

When i run this code i get this error
Segmentation fault (core dump)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You need to add return root or return tmp at the end of add.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading