From ee38dceea244eacdb9d0cbcf7a366231ee31e4f4 Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Wed, 27 Mar 2024 12:10:46 +0100 Subject: [PATCH] tree_remove working --- src/tree.c | 42 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 4 deletions(-) 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) {