sandbox: btree: deletion fixup bugfix

This commit is contained in:
2023-01-24 21:26:22 +00:00
parent bf8da4dbb5
commit dbf3ad101d
2 changed files with 78 additions and 40 deletions

View File

@@ -222,15 +222,18 @@ static void delete_fixup(btree_t *tree, btree_node_t *w)
int nr_rotations = 0;
while (z) {
printf("bf(z)=%d\n", bf(z));
printf("bf(z->b_left)=%d\n", bf(z->b_left));
if (bf(z) > 1) {
if (bf(z->b_left) <= 0) {
if (bf(z->b_right) >= 0) {
rotate_left(tree, z);
update_height_to_root(z);
} else {
rotate_double_left(tree, z);
rotate_double_left(tree, z); // <==
}
} else if (bf(z) < -1) {
if (bf(z->b_right) > 0) {
if (bf(z->b_left) <= 0) {
rotate_right(tree, z);
update_height_to_root(z);
} else {
@@ -354,62 +357,78 @@ static btree_node_t *replace_node_with_one_subtree(btree_t *tree, btree_node_t *
return w;
}
static btree_node_t *replace_node_with_two_subtrees(btree_t *tree, btree_node_t *node)
static btree_node_t *replace_node_with_two_subtrees(btree_t *tree, btree_node_t *z)
{
debug_msg("remove_node_with_two_subtrees()\n");
btree_node_t *cur = node->b_left;
while (cur->b_right) {
cur = cur->b_right;
/* x will replace z */
btree_node_t *x = z->b_left;
while (x->b_right) {
x = x->b_right;
}
btree_node_t *p = cur->b_parent;
btree_node_t *k = p;
/* y is the node that will replace x (if x has a left child) */
btree_node_t *y = x->b_left;
if (IS_LEFT_CHILD(p, cur)) {
p->b_left = NULL;
} else {
p->b_right = NULL;
/* w is the starting point for the height update and fixup */
btree_node_t *w = x;
if (w->b_parent != z) {
w = w->b_parent;
}
p = node->b_parent;
if (p) {
if (IS_LEFT_CHILD(p, node)) {
p->b_left = cur;
} else {
p->b_right = cur;
}
if (y) {
w = y;
}
cur->b_left = node->b_left;
cur->b_right = node->b_right;
cur->b_height = node->b_height;
cur->b_parent = p;
btree_node_t *w = cur;
if (!p) {
tree->b_root = cur;
if (IS_LEFT_CHILD(x->b_parent, x)) {
x->b_parent->b_left = y;
} else if (IS_RIGHT_CHILD(x->b_parent, x)) {
x->b_parent->b_right = y;
}
if (tree->b_root->b_left) {
tree->b_root->b_left->b_parent = tree->b_root;
if (y) {
y->b_parent = x->b_parent;
}
if (tree->b_root->b_right) {
tree->b_root->b_right->b_parent = tree->b_root;
if (IS_LEFT_CHILD(z->b_parent, z)) {
z->b_parent->b_left = x;
} else if (IS_RIGHT_CHILD(z->b_parent, z)) {
z->b_parent->b_right = x;
}
x->b_parent = z->b_parent;
x->b_left = z->b_left;
x->b_right = z->b_right;
if (x->b_left) {
x->b_left->b_parent = x;
}
if (x->b_right) {
x->b_right->b_parent = x;
}
if (!x->b_parent) {
tree->b_root = x;
}
btree_node_t *cur = w;
while (cur) {
update_height(cur);
cur = cur->b_parent;
}
printf("w=%llu, h:%u\n", w->b_key, w->b_height);
return w;
}
void btree_delete(btree_t *tree, btree_node_t *node)
{
if (!node->b_owner) {
return;
}
assert(node->b_owner == tree);
btree_node_t *w = NULL;
@@ -421,6 +440,8 @@ void btree_delete(btree_t *tree, btree_node_t *node)
w = replace_node_with_two_subtrees(tree, node);
}
btree_print(tree->b_root, 0);
if (w) {
delete_fixup(tree, w);
}