簡體   English   中英

C段錯誤中的二叉搜索樹

[英]Binary Search Tree in C Segmentation Fault

我一直在嘗試用 C 實現一個簡單的二叉搜索樹作為練習。 我可以將元素插入樹中,但在某些點(我無法弄清楚在哪里)我遇到了分段錯誤。

這是我的代碼:

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

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

void insert(struct node *treeNode, int key);
void outputTree(struct node *root);

int main(){
    //Store how many numbers the user will enter
    printf("How many numbers will you enter? > ");
    int numNumbers;
    scanf("%d", &numNumbers);

    //Create a root node
    struct node root;
    root.key = -1; //-1 Means the root node has not yet been set
    root.right = NULL;
    root.left = NULL;

    //Now iterate numNumbers times
    int i;
    for(i = 1; i <= numNumbers; ++i){
        int input;
        scanf("%d", &input);
        insert(&root, input);
    }

    outputTree(&root);

    return 0;
}

void insert(struct node *treeNode, int key){
    //First check if the node is the root node
    if((*treeNode).key == -1){
        printf("Root node is not set\n");
        (*treeNode).key = key; //If the root node hasn't been initialised
    }
    else {
        //Create a child node containing the key
        struct node childNode;
        childNode.key = key;
        childNode.left = NULL;
        childNode.right = NULL;

        //If less than, go to the left, otherwise go right
        if(key < (*treeNode).key){
            if((*treeNode).left != NULL){ 
                printf("Left node is not null, traversing\n");
                insert((*treeNode).left, key);
            }
            else {
                printf("Left node is null, creating new child\n");
                (*treeNode).left = &childNode;
            }
        }
        else {
            //Check if right child is null
            if((*treeNode).right != NULL){
                printf("Right node is not null, traversing...\n");
                insert((*treeNode).right, key);
            }
            else {
                printf("Right node is null, creating new child\n");
                (*treeNode).right = &childNode;
            }
        }
    }
}

void outputTree(struct node *root){
    //Traverse left
    if((*root).left != NULL){
        outputTree((*root).left);
    }
    printf("%d\n", (*root).key);
    if((*root).right != NULL){
        outputTree((*root).right);
    }
}

在寫這個問題時,我剛剛想到,是否在堆棧上創建了子節點,所以當遞歸調用返回時,樹中的引用指向一個不再存在的結構?

這里有什么問題?

謝謝

您通過靜態分配在堆棧上創建子節點。 當插入方法完成時,子引用變為無效。 您應該對 malloc 使用動態分配。

struct node *new_node(int key, struct node *left, struct node *right) {
    struct node *this = malloc(sizeof *this);
    this->key = key;
    this->left = left;
    this->right = right;
    return this;
}

不要忘記使用 free 函數釋放所有分配。

編輯:所以創建根只需使用

struct node *root = new_node(-1, NULL, NULL);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM