From d93788d6e7b9a4b2874dddd449d85a07aaa7a81c Mon Sep 17 00:00:00 2001 From: Mineplay Date: Wed, 3 Sep 2025 13:18:32 -0500 Subject: [PATCH] perf(search tree): improved in order traversal performance --- Include/Fledasty/Trees/BinarySearchTree.h | 42 ++++++++++------------- 1 file changed, 18 insertions(+), 24 deletions(-) diff --git a/Include/Fledasty/Trees/BinarySearchTree.h b/Include/Fledasty/Trees/BinarySearchTree.h index 51057af..d6cb787 100644 --- a/Include/Fledasty/Trees/BinarySearchTree.h +++ b/Include/Fledasty/Trees/BinarySearchTree.h @@ -230,35 +230,29 @@ FledastyError fledasty_binary_search_tree_##name##_in_order_traversal(FledastyBi return FLEDASTY_ERROR_FAILED_ALLOCATION; \ } \ \ - size_t current_index = 0, current_stack_size = 0; \ - bool *added_stack = (bool*)hallocy_calloc(current_binary_search_tree->size + 1, sizeof(bool)); \ - if (added_stack == NULL) { \ - return FLEDASTY_ERROR_FAILED_ALLOCATION; \ - } \ - \ + size_t current_stack_size = 0; \ + FledastyBinarySearchTreeNode_##name *previous_node = NULL; \ FledastyBinarySearchTreeNode_##name *current_node = current_binary_search_tree->top; \ while (current_stack_size < current_binary_search_tree->size) { \ - if (current_node->left != NULL && !added_stack[current_index + 1]) { \ - current_node = current_node->left; \ - current_index += 1; \ - } else if (!added_stack[current_index]) { \ + if (current_node->parent == previous_node) { \ + previous_node = current_node; \ + if (current_node->left != NULL) { \ + current_node = current_node->left; \ + } \ + } else if (current_node->right != NULL && (current_node->left == NULL || current_node->left == previous_node)) { \ (*out)[current_stack_size] = current_node; \ current_stack_size += 1; \ - added_stack[current_index] = true; \ - if (current_node->right != NULL) { \ - current_node = current_node->right; \ - current_index += 1; \ - added_stack[current_index] = false; \ - } \ - } else { \ - current_node = current_node->parent; \ - added_stack[current_index + 1] = false; \ - current_index -= 1; \ - } \ - } \ \ - if (hallocy_free(added_stack) != HALLOCY_ERROR_NONE) { \ - return FLEDASTY_ERROR_FAILED_ALLOCATION; \ + previous_node = current_node; \ + current_node = current_node->right; \ + } else { \ + if (current_node->right != previous_node) { \ + (*out)[current_stack_size] = current_node; \ + current_stack_size += 1; \ + } \ + previous_node = current_node; \ + current_node = current_node->parent; \ + } \ } \ \ return FLEDASTY_ERROR_NONE; \