wrote first version of addToTree() and wrote new recursive function addToTreeRec()
This commit is contained in:
parent
03495bddf0
commit
7dca38c37f
56
bintree.c
56
bintree.c
@ -18,23 +18,61 @@
|
|||||||
void clearTree (TreeNode *root);
|
void clearTree (TreeNode *root);
|
||||||
unsigned int treeSize (const TreeNode *root);
|
unsigned int treeSize (const TreeNode *root);
|
||||||
|
|
||||||
|
// selfdeclaredfunctions
|
||||||
|
TreeNode *addToTreeRec (TreeNode *currentNode, TreeNode *newNode, CompareFctType compareFct, int *isDuplicate);
|
||||||
|
|
||||||
|
|
||||||
// Adds a copy of data's pointer destination to the tree using compareFct for ordering. Accepts duplicates
|
// Adds a copy of data's pointer destination to the tree using compareFct for ordering. Accepts duplicates
|
||||||
// if isDuplicate is NULL, otherwise ignores duplicates and sets isDuplicate to 1 (or to 0 if a new entry is added).
|
// if isDuplicate is NULL, otherwise ignores duplicates and sets isDuplicate to 1 (or to 0 if a new entry is added).
|
||||||
|
|
||||||
|
// returned Value is new root?
|
||||||
TreeNode *addToTree(TreeNode *root, const void *data, size_t dataSize, CompareFctType compareFct, int *isDuplicate)
|
TreeNode *addToTree(TreeNode *root, const void *data, size_t dataSize, CompareFctType compareFct, int *isDuplicate)
|
||||||
{
|
{
|
||||||
|
// create a node
|
||||||
|
TreeNode *newNode;
|
||||||
|
|
||||||
if (root == NULL)
|
|
||||||
{
|
newNode = calloc(1, sizeof(TreeNode));
|
||||||
//root setzen
|
newNode->data = calloc(1, dataSize);
|
||||||
}
|
newNode->left = NULL;
|
||||||
else
|
newNode->right = NULL;
|
||||||
{
|
memcpy(newNode->data, data, dataSize);
|
||||||
//vergleichen und dann je links und rechts weiter
|
|
||||||
// mit neuer rekursiver funktion?
|
|
||||||
// in dieser jeweils nachschauen ob duplikat
|
return addToTreeRec(root, newNode, compareFct, isDuplicate);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
TreeNode *addToTreeRec(TreeNode *currentNode, TreeNode *newNode, CompareFctType compareFct, int *isDuplicate)
|
||||||
|
{
|
||||||
|
if (currentNode == NULL)
|
||||||
|
{
|
||||||
|
isDuplicate = 0;
|
||||||
|
return newNode;
|
||||||
|
}
|
||||||
|
else if (compareFct(newNode->data, currentNode->data) < 0)
|
||||||
|
{
|
||||||
|
currentNode->left = addToTreeRec(currentNode->left, newNode, compareFct, isDuplicate);
|
||||||
|
}
|
||||||
|
else if (compareFct(newNode->data, currentNode->data) > 0)
|
||||||
|
{
|
||||||
|
currentNode->right = addToTreeRec(currentNode->right, newNode, compareFct, isDuplicate);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
//duplicate
|
||||||
|
if (isDuplicate == NULL)
|
||||||
|
{
|
||||||
|
return newNode;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
isDuplicate = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
return currentNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user