From 70119f897aa6b2fac8d0edcff64a91b87d108b56 Mon Sep 17 00:00:00 2001 From: pvtrx Date: Fri, 12 Dec 2025 08:18:04 +0100 Subject: [PATCH] implemented first draft of addToTree --- bintree.c | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/bintree.c b/bintree.c index b04b4ec..b194df7 100644 --- a/bintree.c +++ b/bintree.c @@ -1,3 +1,4 @@ +#include #include #include "stack.h" #include "bintree.h" @@ -12,7 +13,42 @@ // if isDuplicate is NULL, otherwise ignores duplicates and sets isDuplicate to 1 (or to 0 if a new entry is added). TreeNode *addToTree(TreeNode *root, const void *data, size_t dataSize, CompareFctType compareFct, int *isDuplicate) { + if (root == NULL) { + TreeNode *newNode = (TreeNode *)malloc(sizeof(TreeNode)); + if (newNode == NULL) { + return NULL; + } + newNode->data = malloc(dataSize); + if (newNode->data == NULL) { + free(newNode); + return NULL; + } + memcpy(newNode->data, data, dataSize); + newNode->left = NULL; + newNode->right = NULL; + + if (isDuplicate != NULL) { + *isDuplicate = 0; + } + return newNode; + } + + int cmp = compareFct(data, root->data); + + if (cmp == 0 && isDuplicate != NULL) { + *isDuplicate = 1; + return root; + } + + if (cmp < 0) { + root->left = addToTree(root->left, data, dataSize, compareFct, isDuplicate); + } else { + /* Insert duplicates on the right side if they are allowed (isDuplicate == NULL). */ + root->right = addToTree(root->right, data, dataSize, compareFct, isDuplicate); + } + + return root; } // Iterates over the tree given by root. Follows the usage of strtok. If tree is NULL, the next entry of the last tree given is returned in ordering direction.