From 1d8550d653cec110403f7cfe7d18723d188f3dd0 Mon Sep 17 00:00:00 2001 From: Mineplay Date: Sun, 31 Aug 2025 08:26:14 -0500 Subject: [PATCH] perf(search tree): improved insertion and replacement performance --- Include/Fledasty/Trees/BinarySearchTree.h | 53 ++++++++++------------- 1 file changed, 24 insertions(+), 29 deletions(-) diff --git a/Include/Fledasty/Trees/BinarySearchTree.h b/Include/Fledasty/Trees/BinarySearchTree.h index 057a5ca..35fa82e 100644 --- a/Include/Fledasty/Trees/BinarySearchTree.h +++ b/Include/Fledasty/Trees/BinarySearchTree.h @@ -95,45 +95,40 @@ FledastyError fledasty_binary_search_tree_##name##_insert(FledastyBinarySearchTr return FLEDASTY_ERROR_INVALID_POINTER; \ } \ \ - FledastyBinarySearchTreeNode_##name *new_node = (FledastyBinarySearchTreeNode_##name*)hallocy_malloc(sizeof(FledastyBinarySearchTreeNode_##name)); \ - if (new_node == NULL) { \ - return FLEDASTY_ERROR_FAILED_ALLOCATION; \ + FledastyBinarySearchTreeNode_##name *previous_node = NULL; \ + FledastyBinarySearchTreeNode_##name *current_node = current_binary_search_tree->top; \ + while (current_node != NULL) { \ + if (compare_key_function(key, current_node->key)) { \ + current_node->value = value; \ + return FLEDASTY_ERROR_VALUE_REPLACED; \ + } \ + \ + previous_node = current_node; \ + if (key_less_than_function(key, current_node->key)) { \ + current_node = previous_node->left; \ + } else { \ + current_node = previous_node->right; \ + } \ } \ \ + FledastyBinarySearchTreeNode_##name *new_node = (FledastyBinarySearchTreeNode_##name*)hallocy_malloc(sizeof(FledastyBinarySearchTreeNode_##name)); \ + if (new_node == NULL) { \ + return FLEDASTY_ERROR_FAILED_ALLOCATION; \ + } \ + \ + new_node->parent = previous_node; \ new_node->left = NULL; \ new_node->right = NULL; \ - new_node->parent = NULL; \ \ new_node->key = key; \ new_node->value = value; \ \ - if (current_binary_search_tree->top == NULL) { \ + if (previous_node == NULL) { \ current_binary_search_tree->top = new_node; \ + } else if (key_less_than_function(key, previous_node->key)) { \ + previous_node->left = new_node; \ } else { \ - FledastyBinarySearchTreeNode_##name *current_node = current_binary_search_tree->top; \ - while (new_node->parent == NULL) { \ - if (compare_key_function(key, current_node->key)) { \ - current_node->value = value; \ - hallocy_free(new_node); \ - return FLEDASTY_ERROR_VALUE_REPLACED; \ - } \ - \ - if (key_less_than_function(key, current_node->key)) { \ - if (current_node->left == NULL) { \ - new_node->parent = current_node; \ - current_node->left = new_node; \ - } else { \ - current_node = current_node->left; \ - } \ - } else { \ - if (current_node->right == NULL) { \ - new_node->parent = current_node; \ - current_node->right = new_node; \ - } else { \ - current_node = current_node->right; \ - } \ - } \ - } \ + previous_node->right = new_node; \ } \ \ current_binary_search_tree->size += 1; \