简体   繁体   中英

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. After the BST is created, I want to find the closest value to my key which is 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. 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:

在此处输入图像描述

Here is the correct search 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); 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM