[英]Searching BST element function in C
我认为这一定是简单的问题,但我不知道出了什么问题..
gdb 说
Program received signal SIGSEGV, Segmentation fault.
0x000055555555543e in searchNode (root=0x0, X=1) at problem1.c:40
40 while(cursor->value != X || cursor != NULL)
插入和搜索功能
typedef struct TreeNode
{
int value;
struct TreeNode *left;
struct TreeNode *right;
struct TreeNode *parent;
} tree;
tree *insert(tree *root, int X)
{
tree *cursor = root;
tree *parent;
while(cursor != NULL)
{
parent = cursor;
if(X >= cursor->value)
cursor = cursor->right;
else
cursor = cursor->left;
}
cursor = (tree *)malloc(sizeof(tree));
cursor->value = X;
cursor->left = cursor->right = NULL;
cursor->parent = parent;
return cursor;
}
tree *searchNode(tree *root, int X)
{
tree *cursor = root;
while(cursor->value != X || cursor != NULL)
{
if(X >= cursor->value)
cursor = cursor->right;
else
cursor = cursor->left;
}
if(cursor == NULL)
return NULL;
else if(cursor->value == X)
return cursor;
}
主功能
int main()
{
tree *root = (tree *)malloc(sizeof(tree));
root = NULL;
insert(root, 10);
insert(root ,20);
insert(root, 5);
insert(root, 1);
insert(root, 15);
insert(root, 20);
insert(root, 30);
insert(root, 100);
insert(root, 40);
insert(root, 50);
node = searchNode(root, 1);
}
据我所知,当我引用 NULL 指针时,大多会出现分段错误,但我不认为搜索功能是错误的。 我想我在插入函数或初始化树根时犯了错误,但我不知道出了什么问题..
出于好奇,我查看了代码。
我不认为搜索功能是错误的
我不同意!
看这行代码:
while(cursor->value != X || cursor != NULL)
如果cursor
为NULL
会发生什么? cursor->value
被访问,这是未定义的行为(因为访问NULL
是不允许的)。 这值得一个Segmentation fault
。
更好的是:
while (cursor != NULL && cursor->value != X)
或更短:
while (cursor && cursor->value != X)
从 gdb 中调用 OP 的片段
Program received signal SIGSEGV, Segmentation fault.
0x000055555555543e in searchNode (root=0x0, X=1) at problem1.c:40
40 while(cursor->value != X || cursor != NULL)
(我第一眼没有意识到)这对我来说听起来很合理。
根据( root = 0x0
), searchNode()
似乎是为空树调用的( root
为NULL
)。 因此, tree *cursor = root;
用NULL
指针(以及上面的其余部分)初始化cursor
。
您的insert
函数的问题在于它无法更新root
的值。 您返回新的叶节点,但这对您跟踪root
可能是什么没有多大用处。
为了能够改变root
你必须传入一个指向它的指针,例如:
insert(&root, 10);
然后你可以像这样改变你的功能。 它沿着树向下遍历,传入指向当前节点左侧或右侧分支的指针,直到发现该节点尚不存在,然后创建它。
tree *insert(tree **root, int X)
{
if(*root == NULL)
{
*root = (tree *)malloc(sizeof(tree));
(*root)->value = X;
(*root)->left = (*root)->right = (*root)->parent = NULL;
return(*root);
}
else
{
tree *ret;
if(X >= (*root)->value)
{
ret=insert(&(*root)->right, X);
(*root)->right->parent=*root;
}
else
{
ret=insert(&(*root)->left, X);
(*root)->left->parent=*root;
}
return ret;
}
}
所以当你第一次调用它时,它会为你填充root
。 第二次,它将传入指向root->right
的指针,这将成为insert
函数中的新root
,因为它是NULL
,它将被创建。 然后为了完整起见,它更新parent
链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.