diff --git a/src/tree.c b/src/tree.c index 43e2891..acab0d7 100644 --- a/src/tree.c +++ b/src/tree.c @@ -58,11 +58,45 @@ bool tree_contains(Node *node, int data) { } int tree_remove(Node **node, int data) { - if (node == NULL) - return false; - // TODO + if (*node == NULL) + return 0; - 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) {