繁体   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