From 76ca84f72e10ec572318b26bf78aae177e57c1b0 Mon Sep 17 00:00:00 2001 From: Gregory Lirent Date: Thu, 25 Aug 2022 21:43:31 +0300 Subject: [PATCH] Fix rbtree inorder iter --- src/rbtree.c | 61 ++++++++++++++++++---------------------------------- 1 file changed, 21 insertions(+), 40 deletions(-) diff --git a/src/rbtree.c b/src/rbtree.c index bd8c6b1..d93466b 100644 --- a/src/rbtree.c +++ b/src/rbtree.c @@ -196,60 +196,41 @@ void* libcdsb_builtin_rbtree_node_create(void* v, rbnode_t* p, int c, int n) { stack_t libcdsb_builtin_rbtree_iter_inorder(rbnode_t** root, bool reverse) { - rbnode_t *n, hack; - stack_t z, *bot; + stack_t z, *cur; + rbnode_t *n; memset(&z, 0, sizeof(z)); - if (rbnode_is_empty(*root)) + if (rbnode_is_empty(n = *root)) return z; - hack.right = *root; - n = &hack; + while (!rbnode_is_empty(n)) { + stack_insert(&z, n); + n = n->left; + } - for (bot = &z;;) { - for (;;) { - if (rbnode_is_empty(n->right)) { + cur = z.prev; + z.value = z.prev->value; + z.prev = z.prev->prev; - if (rbnode_is_root(n->parent) || n->parent->left == n) { - n = n->parent; - break; - } else n = n->parent; + free(cur); - if (rbnode_is_root(n->parent) || n->parent->left == n) { - n = n->parent; - break; - } + cur = &z; - do { - n = n->parent; - } while (n->parent->right == n); + while ((cur = cur->prev)) { + n = cur->value; - n = n->parent; - } else { - n = n->right; + if (!rbnode_is_empty(n->right)) { + n = n->right; - while (!rbnode_is_empty(n->left)) - n = n->left; - - break; - } - - if (rbnode_is_root(n)) { - bot = z.prev; - z = *bot; - - free(bot); - - if (reverse) - stack_reverse(&z); - - return z; + while (!rbnode_is_empty(n)) { + stack_insert(cur, n); + n = n->left; } } - - bot = stack_insert(bot, n); } + + return z; }