【发布时间】:2017-07-26 00:20:05
【问题描述】:
我刚开始学习 C 语言中的树,但我的代码不断出现分段错误。该代码旨在创建树,然后返回树中的最小值和最大值。我查看了其他人的代码,但似乎找不到我所犯的错误。如果有人能发现它,那将非常有帮助。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node{
int data;
struct node* right;
struct node* left;
}node;
node* Insert(node* root, int data);
int Min(node* root);
int Max(node* root);
node* GetNewNode(int data);
int main(void){
int min, max, data, x;
node* root = NULL;
printf("how many elements would you like to be in the tree\n");
scanf("%i", &x);
for(int i = 0; i < x; i++){
scanf("%i", &data);
root = Insert(root, data);
}
min = Min(root);
max = Max(root);
printf("the min value is %i, and the max value is %i\n", min, max);
}
node* Insert(node* root, int data){
if(root == NULL){
root = GetNewNode(data);
}
else if(data <= root->data){
root->left = Insert(root->left, data);
}
else{
root->right= Insert(root->right, data);
}
return root;
}
node* GetNewNode(int data){
node* newNode = (node*)malloc(sizeof(node*));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
int Min(node* root){
node* temp = root;
if(root->left == NULL){
return root->data;
}
else{
return Min(root->left);
}
}
int Max(node* root){
node* temp = root;
if(root->right == NULL){
return root->data;
}
else{
return Max(root->right);
}
}
【问题讨论】:
-
node* newNode = (node*)malloc(sizeof(node*));-->node* newNode = (node*)malloc(sizeof(node));或node* newNode = malloc(sizeof(*newNode)); -
这是一个很好的捕捉@BLUEPIXY。 Mohammed 如果您在 GDB 下执行并检查回溯,那就太好了,这也是学习调试的好机会。
标签: c tree binary-search-tree