簡體   English   中英

如何在 C 中的二叉搜索樹中找到最接近或精確的值

[英]How to find the closest or exact value in a binary search tree in C

我創建了一個 C 程序,其中將充滿doubles的排序數組轉換為二叉搜索樹。 創建 BST 后,我想找到最接近我的密鑰的值 1.0。 一旦達到最接近的值,我的程序就會崩潰。 但是,如果我的密鑰是可以在 BST 中找到的精確值,它就可以正常工作並打印“找到”消息。 任何人都知道我該如何解決這個問題?

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

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

struct node* createnewnode(double data);
struct node* bstcreate(double* arr, int start, int end); 
struct node* search(struct node* root, double key);

int main(int argc, char *argv[]) {
    
    double array[] = {-4.526682861, -3.682840076, -2.953453251,-1.709721126, -0.936102616, 
    0.18335189, 1.038874246, 2.618022636, 3.259094511, 4.198243959};
    
    int index = sizeof(array) / sizeof(array[0])-1;
    //printf("%d\n", index);
    
    struct node *root = bstcreate(array, 0, index);
    search(root, 1.0);
    //search(root, 1.538874246);
    return 0;
}

struct node* bstcreate(double* arr, int start, int end) 
{ 
    if (start > end) 
      return NULL; 
  
    int mid = (start + end)/2; 
    struct node *root = createnewnode(arr[mid]); 

    root->left =  bstcreate(arr, start, mid-1); 
    root->right = bstcreate(arr, mid+1, end); 
  
    return root; 
} 
  
struct node* createnewnode(double data)  
{ 
    struct node* node = (struct node*)malloc(sizeof(struct node)); 
    node->data = data; 
    node->left = NULL; 
    node->right = NULL; 
  
    return node; 
}

struct node* search(struct node* root, double key) {
    printf("%lf\n",root->data); 
    
    if (root == NULL || root->data == key) {
        printf("Found: %lf\n", root->data);
        return root; 
    }
    
    else if (root->data < key) {
        return search(root->right, key);
    }
    else {
        return search(root->left, key); 
    }
}

這是 output 在程序崩潰前打印的內容:

在此處輸入圖像描述

下面是正確的搜索 function:

struct node* search(struct node* root, double key) {
     
    if (root == NULL) {
        return root; 
    }
    printf("%lf\n",root->data);
    
    if (root->data == key) {
        printf("Found: %lf\n", root->data);
        return root; 
    }
    else if (root->data < key) {
        return search(root->right, key);
    }
    else {
        return search(root->left, key); 
    }
}

暫無
暫無

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

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