diff --git a/Startcode/bintree.c b/Startcode/bintree.c index 8fd8907..9a2510a 100644 --- a/Startcode/bintree.c +++ b/Startcode/bintree.c @@ -1,3 +1,4 @@ +#include #include #include "stack.h" #include "bintree.h" @@ -113,3 +114,19 @@ unsigned int treeSize(const TreeNode *const root) return treeSize(root->left) + treeSize(root->right) + 1; } + +void *toArray(TreeNode *const root, const size_t dataSize) { + if (root == NULL) return NULL; + + const unsigned int elementCount = treeSize(root); + unsigned char *array = calloc(elementCount, dataSize); + if (array == NULL) return NULL; + + unsigned int index = 0; + for (void *element = nextTreeData(root); element != NULL && index < elementCount; element = nextTreeData(NULL)) { + memcpy(array + index * dataSize, element, dataSize); + index++; + } + + return array; +} diff --git a/Startcode/bintree.h b/Startcode/bintree.h index 25e16b2..5d2c427 100644 --- a/Startcode/bintree.h +++ b/Startcode/bintree.h @@ -23,5 +23,7 @@ void *nextTreeData(TreeNode *root); void clearTree(TreeNode *root); // Returns the number of entries in the tree given by root. unsigned int treeSize(const TreeNode *root); +// Converts a tree to an array where all values are sorted. +void *toArray(TreeNode *const root, const size_t dataSize); -#endif \ No newline at end of file +#endif diff --git a/Startcode/test_bintree.c b/Startcode/test_bintree.c index 6ff2277..63436ee 100644 --- a/Startcode/test_bintree.c +++ b/Startcode/test_bintree.c @@ -29,6 +29,14 @@ static void test_addToTreeAllNullReturnsNull(void) TEST_ASSERT_NULL(addToTree(NULL, NULL, 0, NULL, NULL)); } +static void test_toArrayWorks(void) +{ + TreeNode *const tree = buildTree(); + const int *array = toArray(tree, sizeof(int)); + const int expected[4] = {1, 2, 3, 4,}; + TEST_ASSERT_EQUAL_INT_ARRAY(expected, array, 4); +} + static void test_addToTreeBuildsTreeInOrder(void) { const TreeNode *const tree = buildTree(); @@ -141,6 +149,7 @@ int main() printf("\n============================\nbinary tree tests\n============================\n"); RUN_TEST(test_addToTreeAllNullReturnsNull); + RUN_TEST(test_toArrayWorks); RUN_TEST(test_addToTreeBuildsTreeInOrder); RUN_TEST(test_addToTreeReportsNoDuplicates); RUN_TEST(test_addToTreeReportsDuplicates);