如何在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,index);
    search(root,1.0);
    //search(root,1.538874246);
    return 0;
}

struct node* bstcreate(double* arr,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); 
    }
}

这是程序崩溃前输出的输出:

enter image description here

解决方法

这是正确的搜索功能:

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); 
    }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...