我正在研究从二叉搜索树中删除具有给定密钥的节点的算法。到目前为止,我已经能够想出下面的代码:使用父指针从二叉搜索树中删除节点
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <time.h>
typedef int ElType;
typedef struct Tree {
ElType key;
struct Tree *left;
struct Tree *right;
struct Tree *parent;
} Tree;
Tree* InsertBST(Tree* t, int k)
{
if (t == NULL) {
Tree* w = (Tree*) malloc(sizeof(Tree));
w->key = k;
w->left = NULL;
w->right = NULL;
w->parent = NULL;
return w;
}
if (k <= t->key) {
t->left = InsertBST(t->left, k);
t->left->parent = t;
}
else {
t->right = InsertBST(t->right, k);
t->right->parent = t;
}
return t;
}
Tree* DeleteMaxOfBST(Tree* t, ElType *deleted_value)
{
if (t == NULL) {
*deleted_value = -1;
return NULL;
}
if (t->right == NULL) {
*deleted_value = t->key;
Tree* w = t->left;
w->parent = t->parent;
free(t);
return w;
}
t->right = DeleteMaxOfBST(t->right, deleted_value);
return t;
}
Tree* DeleteNodeOfBST(Tree* t, int k)
{
if (t == NULL) return NULL;
if (k < t->key) {
t->left = DeleteNodeOfBST(t->left, k);
return t;
}
else if (k > t->key) {
t->right = DeleteNodeOfBST(t->right, k);
return t;
}
else if (t->left == NULL) {
Tree* w = t->right;
w->parent = t->parent;
free(t);
return w;
}
else {
ElType max_left;
t->left = DeleteMaxOfBST(t->left, &max_left);
t->key = max_left;
return t;
}
}
总的想法是,我想用指针与BST合作,父节点,并能删除与哪个键我的一个节点指定的同时保留BST的结构。
我的代码适用于某些树中的某些键,但是对于没有任何明显模式的其他键会崩溃。然后我得到了以下错误:
Segmentation fault (core dumped)
我倾向于认为我已经搞砸指针指向父节点,但不能完全准确判断故障。我对C相对来说比较陌生,所以我很感激任何评论,指针是否实际上是这里的问题,以及如何解决这个问题。
如果您在调试器下运行您的代码,它应该确定负责该段错误的代码,并让您检查负责该代码的数据。这很可能是因为之前发生的数据损坏*而产生的问题,但至少可以让您看到某些东西。 –
如果你想让我们看看它,那么我们通常希望看到一个[mcve],在这种情况下,它至少会包含一系列的插入和删除操作,从而可以重现错误。 –
假设只有一个节点被添加到树中,然后用匹配键调用'DeleteNodeOfBST()'。 '树* w = t->正确;' - >'w'为'NULL',然后'w-> parent'为UB。 – chux