所以我正在学习C中的数据结构,二进制搜索树给了我一段艰难的时间,我运行gdb来查看seg故障在哪一行,它在第77行(用代码标记)。我似乎不明白为什么会发生这种事,这是我的代码,提前谢谢:

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


typedef struct node{
    int data;
    struct node* left;
    struct node* right;
} node;
node* getNewNode();
node* insert();
bool searchTree();
int getMin();


int main(int argc, char const *argv[]){
    srand(time(NULL));
    int random;
    node* root;
    int var;
    printf("Genereting tree with random values...\n");//Adding random numbers
    for(int i=1;i<15;i++){
        random = rand();
        insert(root, random);
        printf("%d\n", random);
    }
    printf("Last value added: %d\n", random);

    /*
    printf("Enter number to search: \n");
    scanf(" %d", &var);
    printf("%s\n", searchTree(root, var) ? "true": "false");
    */
    printf("min: %d\n", getMin(root)); //Printing min value

    return 0;
}
node* getNewNode(int data){
    node* newNode = (node*) malloc(sizeof(node));

    newNode->data = data;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}
node* insert(node* root, int data){

    if(root == NULL){
        root = getNewNode(data);
        return root;
    }
    else if(data <= root->data){
        root->left = insert(root->left, data);
    }
    else{
        root->right = insert(root->right, data);
    }
    return root;
    }
bool searchTree(node* root, int data){

    if(root == NULL)
        return false;

    else if(root-> data == data)
        return true;

    else if(data <= root->data)
        return searchTree(root->left, data);
    else
        return searchTree(root->right, data);
}

int getMin(node* root){
    if(root->left == NULL){     //Here is where the error is
        return root->data;
    }

    return getMin(root->left);


}

最佳答案

因为没有分配根,所以出现了分段错误
主目录树的根地址

node* root=0;
    for(int i=1;i<15;i++){
        random = rand();
        root=insert(root, random);//assigning root the starting address of root of tree
        printf("%d\n", random);
    }

关于c - 搜寻最小值时二分搜寻树中的分割错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43333114/

10-10 12:28