簡體   English   中英

使用 C 中的比較 function 遞歸地插入二叉搜索樹

[英]Insert in Binary search tree recursively using comparison function in C

我正在使用嵌套結構來創建 BST,但插入時出現問題,因為我使用了比較 function 來執行此操作! 這是我的比較 function

int compare_doubles(const void* a, const void* b)
 {
    const double* a_ = (const double*)a;
    const double* b_ = (const double*)b;
    return (*a_ > *b_) - (*a_ < *b_);
}



 int compare_int(const void* a, const void* b)
 {
    const int* a_ = (const int*)a;
    const int* b_ = (const int*)b;
    return (*a_ > *b_) - (*a_ < *b_);
}

這是結構

typedef struct tree_t BinarySearchTree; //opaque structure declared on BinarySearchTree.h

struct tree_t{
    int (*comparison)(const void *, const void *);
    struct tree_t* lchild;
    struct tree_t* rchild;
    struct t_node* noeud;
};

struct t_node{
    const void *key;
    const void *data;
    City *city;
};

這是我的 function 來創建一個新的 BST

BinarySearchTree* newBST(int comparison_fn_t(const void *, const void *))
{
    BinarySearchTree *t = (struct tree_t *)malloc(sizeof(struct tree_t));
    t->comparison = comparison_fn_t;
    t->lchild = t->rchild = NULL;
    t->noeud = NULL;  
    return t;
    
}

這是我的插入 function

BinarySearchTree* insertInBST(BinarySearchTree* bst, const void* key, const void* value) {
    BinarySearchTree *t = bst;
    
    
    if (bst->noeud == NULL)
    {
        struct t_node* n = (struct t_node *)malloc(sizeof(struct t_node));
        t->noeud = n;
        t->noeud->data = value;
        t->noeud->key = key;
        return t;
    }

    
    if ((bst->comparison(&key,&(bst->noeud->key))) < 0){
        
        bst->lchild = insertInBST(bst->lchild, key, value);
    }
    else if ((bst->comparison(&key,&(bst->noeud->key))) >= 0){ // handle duplicate keys
        bst->rchild = insertInBST(bst->rchild, key, value);
    }
    return bst;
}

當我嘗試使用這些測試運行我的代碼時,我得到了段錯誤(核心轉儲)這是我的主要 function

int main()
{


    int *t =15;
    int *g = 13;
    int *j =15;
    int *k = 13;

    BinarySearchTree *root = newBST(&compare_doubles);
    insertInBST(root, k,j);
    insertInBST(root, t, g);
    
}```
  1. 當您混合比較 (<, >) 和算術 (-) 運算時,您的比較 function 過於復雜(*a_ > *b_) - (*a_ < *b_) @WhozCraig 建議(a < b)? -1:(b < a)。

  2. 您需要定義結構城市。

  3. 您需要為 malloc #include <stdlib.h>

  4. 在 main 中,您將整數轉換為指針。 第一種情況的編譯器警告是:

    警告:從 'int' 初始化 'int *' 使指針來自 integer 沒有強制轉換 [-Wint-conversion]

    int t = 15; int g = 13 int t = 15; int g = 13和更高版本insertInBST(root, &t, &g)

  5. 在 main 中,您使用了錯誤的比較 function (雙精度而不是 int)。

  6. 我通過 gdb 運行您的代碼,它在if (bst->noeud == 0)中崩潰,因為insertInBST(root, t, g)調用bst->rchild = insertInBST(bst->rchild, key, value)但 bst-> rchild 是 NULL。

  7. 在 insertInBST 中,您只需要進行一次比較即可確定您需要左分支還是右分支。

暫無
暫無

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

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