generated from freudenreichan/info2Praktikum-DobleSpiel
implemented first draft of addToTree
This commit is contained in:
parent
49ba00aad6
commit
70119f897a
36
bintree.c
36
bintree.c
@ -1,3 +1,4 @@
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#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.
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user