这个简单的二叉搜索树会导致段错误:11
。
我无法理解代码的哪一点造成了这个问题。
为什么会出现segmentation failure:11
?
递归binarySerach
函数不会错,因为它来自教科书。
所以我认为我在定义树方面非常无知,可能是关于malloc
的事情。
这样定义treePointer
是否正确?
我完全被错误segmentation failure:11
所诅咒。
我想知道这个错误何时发生。
附注抱歉我的英语不好。
#include <stdio.h>
#include <stdlib.h>
typedef struct element
{
int key;
} element;
typedef struct node *treePointer;
typedef struct node
{
element data;
treePointer leftChild;
treePointer rightChild;
} node;
element* binarySearch(treePointer tree, int key);
int main(void)
{
treePointer *a;
for(int i = 0; i < 10; i++)
{
a[i] = malloc(sizeof(node));
a[i] -> data.key = i * 10;
a[i] -> leftChild = NULL;
a[i] -> rightChild = NULL;
}
a[0] -> leftChild = a[1];
a[0] -> rightChild = a[2];
a[1] -> leftChild = a[3];
a[1] -> rightChild = a[4];
a[2] -> leftChild = a[5];
a[2] -> rightChild = a[6];
a[3] -> leftChild = a[7];
a[3] -> rightChild = a[8];
a[4] -> leftChild = a[9];
element* A = binarySearch(a[0], 30);
printf("%d\n", A -> key);
for(int i = 0; i < 10; i++)
{
free(a[i]);
}
}
element* binarySearch(treePointer tree, int key)
{
if(!tree) return NULL;
if(key == tree -> data.key) return &(tree -> data);
if(key < tree -> data.key)
return binarySearch(tree -> leftChild, key);
return binarySearch(tree -> rightChild, key);
}
最佳答案
您还需要为a
分配内存。将其声明更改为:
treePointer *a = malloc(10 * sizeof(treePointer));
并在最后调用free(a);
。此外,它没有找到 key ,因此返回 NULL,这会导致 printf("%d\n", A->key);
出现未定义的行为。但那是因为你的 BST 设置不正确。根元素的键为 0
,它的两个子元素的键为 10
和 20
,这不可能是正确的。
关于c - 这种基本的二叉搜索树算法会导致段错误:11 error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55917698/