2025-12-09 14:41:22 +01:00

128 lines
3.3 KiB
C

#include <string.h>
#include "stack.h"
#include "bintree.h"
// 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).
TreeNode *addToTree(TreeNode *root, const void *data, size_t dataSize,
CompareFctType compareFct, int *isDuplicate)
{
if (data == NULL || compareFct == NULL)
return root;
if (root == NULL)
{
// neuer Knoten
TreeNode *node = malloc(sizeof(TreeNode));
if (node == NULL)
return NULL;
node->data = malloc(dataSize);
if (node->data == NULL)
{
free(node);
return NULL;
}
memcpy(node->data, data, dataSize);
node->left = NULL;
node->right = NULL;
if (isDuplicate != NULL)
*isDuplicate = 0;
return node;
}
int cmp = compareFct(data, root->data);
if (cmp < 0)
{
root->left = addToTree(root->left, data, dataSize, compareFct, isDuplicate);
}
else if (cmp > 0)
{
root->right = addToTree(root->right, data, dataSize, compareFct, isDuplicate);
}
else
{
// Element bereits vorhanden
if (isDuplicate != NULL)
{
*isDuplicate = 1;
// Duplikate werden ignoriert
}
else
{
// Duplikate dürfen eingefügt werden -> wir hängen sie z.B. links an
root->left = addToTree(root->left, data, dataSize, compareFct, NULL);
}
}
return root;
}
// Interner Stack für die Traversierung (strtok-ähnliches Verhalten)
static StackNode *iterStack = NULL;
// Hilfsfunktion: legt ab start alle linken Knoten auf den Stack
static void pushLeftPath(TreeNode *start)
{
while (start != NULL)
{
iterStack = push(iterStack, start);
start = start->left;
}
}
// 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.
// Use your implementation of a stack to organize the iterator. Push the root node and all left nodes first.
// On returning the next element, push the top node and push all its left nodes.
void *nextTreeData(TreeNode *root)
{
if (root != NULL)
{
// neue Traversierung starten: alten Stack aufräumen
if (iterStack != NULL)
{
clearStack(iterStack);
iterStack = NULL;
}
pushLeftPath(root);
}
if (iterStack == NULL)
return NULL;
// Nächsten Knoten holen
TreeNode *node = (TreeNode *)top(iterStack);
iterStack = pop(iterStack);
// rechten Teilbaum dieses Knotens auf den Stack bringen
if (node->right != NULL)
pushLeftPath(node->right);
return node->data;
}
// Releases all memory resources (including data copies).
void clearTree(TreeNode *root)
{
if (root == NULL)
return;
clearTree(root->left);
clearTree(root->right);
free(root->data);
free(root);
}
// Returns the number of entries in the tree given by root.
unsigned int treeSize(const TreeNode *root)
{
if (root == NULL)
return 0;
return 1u + treeSize(root->left) + treeSize(root->right);
}