#include #include #include "bintree.h" #include "stack.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 (compareFct == NULL || data == NULL || dataSize == 0) return root; // invalid input: do nothing if (root == NULL) { TreeNode *node = (TreeNode *)malloc(sizeof(TreeNode)); if (node == NULL) return NULL; // allocation failed 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 // cmp == 0 -> duplicate { if (isDuplicate != NULL) { *isDuplicate = 1; // ignore duplicate insertion } else { // duplicates allowed: insert to right subtree for stability root->right = addToTree(root->right, data, dataSize, compareFct, isDuplicate); } } return root; } /* Iterates over the tree given by root in-order (ascending order). Follows the usage of strtok: If root != NULL then create/reset iterator for that tree. If root == NULL, continue iteration from last position. Uses stack to manage traversal state. */ void *nextTreeData(TreeNode *root) { // static iterator state static StackNode *iterStack = NULL; static TreeNode *currentRoot = NULL; // initialize iterator for a new tree if (root != NULL) { // clear any previous iterator state clearStack(iterStack); iterStack = NULL; currentRoot = root; // push root and all its left descendants TreeNode *cur = root; while (cur != NULL) { iterStack = push(iterStack, cur); cur = cur->left; } } else { // if user asks to continue but iterator not initialized, nothing to return if (iterStack == NULL) return NULL; } // get next node if (iterStack == NULL) return NULL; // pop the top node TreeNode *node = (TreeNode *)top(iterStack); iterStack = pop(iterStack); // after popping node, push its right child and all left descendants of that right child TreeNode *r = node->right; while (r != NULL) { iterStack = push(iterStack, r); r = r->left; } return node->data; } /* Releases all memory resources (including data copies). */ void clearTree(TreeNode *root) { if (root == NULL) return; if (root->left != NULL) clearTree(root->left); if (root->right != NULL) clearTree(root->right); free(root->data); root->data = NULL; 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 1 + treeSize(root->left) + treeSize(root->right); }