gpt4 book ai didi

c - C 中的二叉搜索树 SEGFAULT

转载 作者:行者123 更新时间:2023-11-30 17:36:39 24 4
gpt4 key购买 nike

我正在用 C 实现 BTS。我已经实现了搜索和插入等基本功能。但我在找到最小元素和最大元素时遇到问题。这是我的代码:

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

//Begin
typedef struct tree{
int data;
struct tree *left;
struct tree *right;
}tree;
//----------------------------------------------------------------------------------------
tree *insert(tree *root, int data);
tree *newnode(int data);
int search(tree *root, int data);
int findMin(tree *root);
int findMax(tree *root);
//-----------------------------------------------------------------------------------------
int main(void){
tree *root = malloc(sizeof(root));
root->left = NULL;
root->right = NULL;
insert(root, 15);
insert(root, 10);
insert(root, 20);
printf("%i\n", search(root ,15));
printf("%i\n", search(root ,20));
printf("%i\n", search(root ,10));
printf("%i\n", search(root ,11));
printf("%i\n", search(root ,17));
printf("%i\n", search(root ,10));
printf("Min: %i\n", findMin(root));
printf("Max: %i\n", findMax(root));
return 0;
}
//-----------------------------------------------------------------------------------------
tree *insert(tree *root, int data){
if(root == NULL){
root = newnode(data);
}

else if(root->data < data)
root->right = insert(root->right,data);
else if(root->data > data)
root->left = insert(root->left,data);
else{
perror("the elements already exist!");
}
return root;
}
//-----------------------------------------------------------------------------------------
tree *newnode(int data){
tree *new = malloc(sizeof(tree));
new->data = data;
new->left = NULL;
new->right = NULL;
return new;
}
//-----------------------------------------------------------------------------------------
int search(tree *root, int data){
if(root == NULL){
return 0;
}
else if(root->data == data){
return root->data;
}
else if (root->data < data){
return search(root->right,data);
}
else if (root->data > data){
return search(root->left,data);
}
else{
perror("Error");
}
}

//-----------------------------------------------------------------------------------------
int findMin(tree *root){
tree *temp = root;
while(temp != NULL){
temp = temp->left;
}
return temp->data;
}
//-----------------------------------------------------------------------------------------
int findMax(tree *root){
tree *temp = root;
while(temp != NULL){
temp = temp->right;
}
return temp->data;
}
//End

问题出在这里:81 返回临时->数据;

即 findmin 函数中的 while 循环

最佳答案

在测试 temp 为 null 之前,您不会返回 temp->data; (null)->data 会给你带来段错误。

尝试像这样修复循环:

int findMin(tree *root){
tree *temp = root;
while(temp -> left != NULL){
temp = temp->left;
}
return temp->data;
}
int findMax(tree *root){
tree *temp = root;
while(temp->right != NULL){
temp = temp->right;
}
return temp->data;
}

关于c - C 中的二叉搜索树 SEGFAULT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22592887/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com