简体   繁体   中英

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)

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM