我正在研究從二叉搜索樹中刪除具有給定密鑰的節點的算法。到目前爲止,我已經能夠想出下面的代碼:使用父指針從二叉搜索樹中刪除節點
#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