diff --git a/Start_Windows/bintree.c b/Start_Windows/bintree.c index c2493c9..b2230e1 100644 --- a/Start_Windows/bintree.c +++ b/Start_Windows/bintree.c @@ -16,7 +16,7 @@ TreeNode *addToTree(TreeNode *root, const void *data, size_t dataSize, CompareFc return NULL; } - if (!root){ + if (!root){ //Neuen Node TreeNode *new = malloc(sizeof(TreeNode)); if (!new){ return NULL; @@ -27,7 +27,7 @@ TreeNode *addToTree(TreeNode *root, const void *data, size_t dataSize, CompareFc return NULL; } - memcpy(new->data, data, dataSize); + memcpy(new->data, data, dataSize); //data übertragen new->left = new->right = NULL; if (isDuplicate){ @@ -58,7 +58,39 @@ TreeNode *addToTree(TreeNode *root, const void *data, size_t dataSize, CompareFc // push the top node and push all its left nodes. void *nextTreeData(TreeNode *root) { - + static StackNode *stack = NULL; + static int initialized = 0; + + if (root != NULL) { // Initialisierung: Stack leeren und mit root + linke elemente befüllen + while (stack != NULL) { + stack = pop(stack); + } + while (root != NULL) { + stack = push(stack, root); + root = root->left; + } + initialized = 1; + } else if (!initialized) { // Noch nicht initialisiert und kein root übergeben + return NULL; + } + + if (stack == NULL) { //Ende + initialized = 0; + return NULL; + } + + TreeNode *topNode = (TreeNode *)top(stack); + stack = pop(stack); + + if (topNode->right != NULL) { + TreeNode *r = topNode->right; + while (r != NULL) { + stack = push(stack, r); + r = r->left; + } + } + + return topNode->data; } // Releases all memory resources (including data copies). diff --git a/Start_Windows/bintree.o b/Start_Windows/bintree.o index 4a63186..2b6e015 100644 Binary files a/Start_Windows/bintree.o and b/Start_Windows/bintree.o differ diff --git a/Start_Windows/bintreeTests.c b/Start_Windows/bintreeTests.c index f637281..d779d3a 100644 --- a/Start_Windows/bintreeTests.c +++ b/Start_Windows/bintreeTests.c @@ -51,6 +51,28 @@ static void testAddToTreeNoData(){ } +static void testNextTreeDataInorderTraversal(){ + TreeNode *root = NULL; + int values[] = {5, 3, 8, 1, 4}; + int expectedInorder[] = {1, 3, 4, 5, 8}; + + for(int i = 0; i < 5; i++) { + root = addToTree(root, &values[i], sizeof(int), compareInt, NULL); //Tree befüllen + } + + void *data = nextTreeData(root); + TEST_ASSERT_NOT_NULL(data); + + for(int i = 0; i < 5; i++){ + TEST_ASSERT_NOT_NULL(data); + TEST_ASSERT_EQUAL_INT(expectedInorder[i], *(int*)data); + data = nextTreeData(NULL); // Nächstes Element + } + + TEST_ASSERT_NULL(data); // Nach letzten Element muss NULL kommen +} + + void setUp(void){ } diff --git a/Start_Windows/runBintreeTests.exe b/Start_Windows/runBintreeTests.exe index bda5ff1..2a470c3 100644 Binary files a/Start_Windows/runBintreeTests.exe and b/Start_Windows/runBintreeTests.exe differ