简体   繁体   English

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

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

I have created a C program where a sorted array full of doubles is converted into a binary search tree.我创建了一个 C 程序,其中将充满doubles的排序数组转换为二叉搜索树。 After the BST is created, I want to find the closest value to my key which is 1.0.创建 BST 后,我想找到最接近我的密钥的值 1.0。 As soon as the closest value is reached, my program crashes.一旦达到最接近的值,我的程序就会崩溃。 However, if my key is an exact value that can be found in the BST, it works perfectly fine and prints the "found" message.但是,如果我的密钥是可以在 BST 中找到的精确值,它就可以正常工作并打印“找到”消息。 Anyone know how I can fix this?任何人都知道我该如何解决这个问题?

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

This is what the output prints before the program crashes:这是 output 在程序崩溃前打印的内容:

在此处输入图像描述

Here is the correct search function:下面是正确的搜索 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