Ich versuche eine Funktion namens 'DeleteElement' zu schreiben, um ein Element im Binary Search Tree zu löschen. Es wird korrekt kompiliert, aber es gibt einen Laufzeitfehler. Bitte helfen Sie mir den Fehler zu debuggen. Danke im Voraus.DeleteElement für binäre Suche Baum gibt Laufzeitfehler?
C Code:
#include <stdio.h>
#include <malloc.h>
struct BinaryTree
{
int data;
struct BinaryTree *left;
struct BinaryTree *right;
};
int FindMin(struct BinaryTree *root)
{
if(root == NULL)
{
return NULL;
}
while(root->left)
{
root = root->left;
}
return root->data;
}
int FindMax(struct BinaryTree *root)
{
if(root == NULL)
{
return NULL;
}
while(root->right)
{
root = root->right;
}
return root->data;
}
struct BinaryTree *DeleteElement(struct BinaryTree *root,int element)
{
struct BinaryTree *temp;
if(root == NULL)
{
printf("Element Not found");
//return NULL;
}
else if(element > root->data)
{
root->right = DeleteElement(root->right,element);
}
else if(element < root->data)
{
root->left = DeleteElement(root->left,element);
}
else
{
if(root->left && root->right)
{
int temp1 = FindMax(root->left);
root->data = temp1;
root->left = DeleteElement(root->left,root->data);
}
else
{
temp = root;
if(root->left == NULL)
{
root = root->right;
}
if(root->right == NULL)
{
root = root->left;
}
free(temp);
}
}
return root;
}
int main()
{
struct BinaryTree * root = (struct BinaryTree *)malloc(sizeof(struct BinaryTree));
root-> data = 7;
struct BinaryTree * l = (struct BinaryTree *)malloc(sizeof(struct BinaryTree));
l -> data = 4;
struct BinaryTree * ll = (struct BinaryTree *)malloc(sizeof(struct BinaryTree));
ll -> data = 2;
ll -> left = ll -> right = NULL;
struct BinaryTree * lr = (struct BinaryTree *)malloc(sizeof(struct BinaryTree));
lr -> data = 5;
lr -> left = lr -> right = NULL;
l -> left = ll;
l -> right = lr;
struct BinaryTree * r = (struct BinaryTree *)malloc(sizeof(struct BinaryTree));
r -> data = 9;
struct BinaryTree * rl = (struct BinaryTree *)malloc(sizeof(struct BinaryTree));
rl -> data = 8;
rl -> left = rl -> right = NULL;
struct BinaryTree * rr = (struct BinaryTree *)malloc(sizeof(struct BinaryTree));
rr -> data = 11;
rr -> left = rr -> right = NULL;
r -> left = rl;
r -> right = rr;
root -> left = l;
root -> right = r;
printf("Max %d\n",FindMax(root));
printf("Min %d\n",FindMin(root));
DeleteElement(root,2);
printf("Max %d\n",FindMax(root));
printf("Min %d\n",FindMin(root));
return 0;
}
Bitte geben Sie den Code, in dem Sie verwenden diese Funktion – teivaz
Alles sieht gut aus in dieser Funktion. Wie @teivaz bemerkte, könnte es im aufrufenden Kontext ein Problem geben. –
Ich habe aktualisiert, um den vollständigen Code einzuschließen. Jetzt können Sie irgendeinen Fehler sehen? –