balance=0时不需要旋转

This commit is contained in:
建峰 2024-06-24 10:15:54 +08:00
parent 4c450fd157
commit 202832f29c
3 changed files with 12 additions and 28 deletions

View File

@ -83,7 +83,7 @@ struct _tree_node
union
{
uint32_t balance;
int32_t balance;
uint32_t color;
};
};
@ -108,7 +108,7 @@ struct _tree
struct _tree_node* (*find_max)(struct _tree* self, struct _tree_node* root);
bool (*rebalance)(struct _tree* self, struct _tree_node* root);
uint32_t (*height)(struct _tree* self, struct _tree_node* root);
int32_t (*height)(struct _tree* self, struct _tree_node* root);
bool (*min)(struct _tree* self, void** obj);
bool (*max)(struct _tree* self, void** obj);

View File

@ -1502,7 +1502,7 @@ static struct _tree_node* tree_trun_right_then_left(struct _tree* self, struct _
return node;
}
uint32_t tree_height(struct _tree* self, struct _tree_node* root)
int32_t tree_height(struct _tree* self, struct _tree_node* root)
{
assert(self != NULL);
if(root == NULL)
@ -1544,7 +1544,11 @@ static bool tree_avl_rebalance(struct _tree* self, struct _tree_node* root)
tree_set_balance(self, root);
int balance = root->balance;
if(balance > 1)
if(balance == 0)
{
// no need to rebalance
}
else if(balance > 1)
{
if(root->right->balance > 0)
{
@ -1806,34 +1810,14 @@ bool tree_avl_delete(struct _tree* self, void* obj)
if(node->left != NULL && node->right != NULL)
{
// have two child
tree_avl_delete_double_child(self, node);
}
else
// else if(node->left != NULL || node->right != NULL)
{
// have singule child or no child
tree_avl_delete_single_child(self, node);
}
// else
// {
// if(node->parent == NULL)
// {
// self->_root = NULL;
// }
// else
// {
// if(node->parent->left == node)
// {
// node->parent->left = NULL;
// }
// else if(node->parent->right == node)
// {
// node->parent->right = NULL;
// }
// self->rebalance(self, node->parent);
// }
// tree_node_free(node);
// }
self->_size--;
return true;

View File

@ -344,13 +344,13 @@ void test_tree_num(void)
for (i = 0; i < len; i++)
{
temp = data[i];
tree->delete(tree, &temp);
printf("delete = ");
tree->print_obj(&temp);
printf("size = %2d\n", tree->size(tree));
tree->delete(tree, &temp);
printf("----- breadth -----\n");
tree->breadth(tree, tree->_root);
printf("----- inorder -----\n");