tree_remove working

This commit is contained in:
Imbus 2024-03-27 12:10:46 +01:00
parent 97571769a3
commit ee38dceea2

View file

@ -58,11 +58,45 @@ bool tree_contains(Node *node, int data) {
} }
int tree_remove(Node **node, int data) { int tree_remove(Node **node, int data) {
if (node == NULL) if (*node == NULL)
return false; return 0;
// TODO
return 0; if ((*node)->data == data) {
// If the node has no children
if ((*node)->left == NULL && (*node)->right == NULL) {
free(*node);
*node = NULL;
return 0;
}
// If the node has one child
if ((*node)->left == NULL) {
Node *temp = *node;
*node = (*node)->right;
free(temp);
return 0;
}
if ((*node)->right == NULL) {
Node *temp = *node;
*node = (*node)->left;
free(temp);
return 0;
}
// If the node has two children
Node *temp = (*node)->right;
while (temp->left != NULL)
temp = temp->left;
(*node)->data = temp->data;
return tree_remove(&(*node)->right, temp->data);
}
if ((*node)->data < data)
return tree_remove(&(*node)->right, data);
return tree_remove(&(*node)->left, data);
} }
void tree_clear(Tree *tree) { void tree_clear(Tree *tree) {