那谁的技术博客

感兴趣领域:高性能服务器编程,存储,算法,Linux内核
随笔 - 210, 文章 - 0, 评论 - 1183, 引用 - 0
数据加载中……

红黑树的实现源码(第二次修订版)

我曾经写过两个两个红黑树的实现, 分别在:
http://www.cppblog.com/converse/archive/2006/10/07/13413.html
http://www.cppblog.com/converse/archive/2007/11/28/37430.html

最近因为要给ccache加入红黑树的支持, 找出来曾经实现的代码作为参考, 这才发现原来的实现都是有问题的,也怪我的测试用例写的不好, 仅仅对插入操作进行了测试, 我向所有因为阅读了这份代码而造成困惑的朋友表示道歉.

这次重新实现, 所有的代码推倒重新编写, 参考了linux内核中红黑树的实现算法, 并且对测试用例进行了加强,希望这是最后一个对红黑树算法的修订版本.

/*-----------------------------------------------------------
    RB-Tree的插入和删除操作的实现算法
    参考资料:
    1) <<Introduction to algorithm>>
    2) http://lxr.linux.no/linux/lib/rbtree.c

    作者:http://www.cppblog.com/converse/
    您可以自由的传播,修改这份代码,转载处请注明原作者

    红黑树的几个性质:
    1) 每个结点只有红和黑两种颜色
    2) 根结点是黑色的
    3)空节点是黑色的(红黑树中,根节点的parent以及所有叶节点lchild、rchild都不指向NULL,而是指向一个定义好的空节点)。
    4) 如果一个结点是红色的,那么它的左右两个子结点的颜色是黑色的
    5) 对于每个结点而言,从这个结点到叶子结点的任何路径上的黑色结点
    的数目相同
-------------------------------------------------------------*/
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef int key_t;
typedef int data_t;

typedef enum color_t
{
    RED = 0,
    BLACK = 1
}color_t;

typedef struct rb_node_t
{
    struct rb_node_t *left, *right, *parent;
    key_t key;
    data_t data;
    color_t color;
}rb_node_t;

/* forward declaration */
rb_node_t* rb_insert(key_t key, data_t data, rb_node_t* root);
rb_node_t* rb_search(key_t key, rb_node_t* root);
rb_node_t* rb_erase(key_t key, rb_node_t* root);

int main()
{
    int i, count = 900000;
    key_t key;
    rb_node_t* root = NULL, *node = NULL;
   
    srand(time(NULL));
    for (i = 1; i < count; ++i)
    {
        key = rand() % count;
        if ((root = rb_insert(key, i, root)))
        {
            printf("[i = %d] insert key %d success!\n", i, key);
        }
        else
        {
            printf("[i = %d] insert key %d error!\n", i, key);
            exit(-1);
        }

        if ((node = rb_search(key, root)))
        {
            printf("[i = %d] search key %d success!\n", i, key);
        }
        else
        {
            printf("[i = %d] search key %d error!\n", i, key);
            exit(-1);
        }
        if (!(i % 10))
        {
            if ((root = rb_erase(key, root)))
            {
                printf("[i = %d] erase key %d success\n", i, key);
            }
            else
            {
                printf("[i = %d] erase key %d error\n", i, key);
            }
        }
    }

    return 0;
}

static rb_node_t* rb_new_node(key_t key, data_t data)
{
    rb_node_t *node = (rb_node_t*)malloc(sizeof(struct rb_node_t));

    if (!node)
    {
        printf("malloc error!\n");
        exit(-1);
    }
    node->key = key, node->data = data;

    return node;
}

/*-----------------------------------------------------------
|   node           right
|   / \    ==>     / \
|   a  right     node  y
|       / \           / \
|       b  y         a   b
 -----------------------------------------------------------*/
static rb_node_t* rb_rotate_left(rb_node_t* node, rb_node_t* root)
{
    rb_node_t* right = node->right;

    if ((node->right = right->left))
    {
        right->left->parent = node;
    }
    right->left = node;

    if ((right->parent = node->parent))
    {
        if (node == node->parent->right)
        {
            node->parent->right = right;
        }
        else
        {
            node->parent->left = right;
        }
    }
    else
    {
        root = right;
    }
    node->parent = right;

    return root;
}

/*-----------------------------------------------------------
|       node           left
|       / \            / \
|    left  y   ==>    a   node
|   / \               / \
|  a   b             b   y
-----------------------------------------------------------*/
static rb_node_t* rb_rotate_right(rb_node_t* node, rb_node_t* root)
{
    rb_node_t* left = node->left;

    if ((node->left = left->right))
    {
        left->right->parent = node;
    }
    left->right = node;

    if ((left->parent = node->parent))
    {
        if (node == node->parent->right)
        {
            node->parent->right = left;
        }
        else
        {
            node->parent->left = left;
        }
    }
    else
    {
        root = left;
    }
    node->parent = left;

    return root;
}

static rb_node_t* rb_insert_rebalance(rb_node_t *node, rb_node_t *root)
{
    rb_node_t *parent, *gparent, *uncle, *tmp;

    while ((parent = node->parent) && parent->color == RED)
    {
        gparent = parent->parent;

        if (parent == gparent->left)
        {
            uncle = gparent->right;
            if (uncle && uncle->color == RED)
            {
                uncle->color = BLACK;
                parent->color = BLACK;
                gparent->color = RED;
                node = gparent;
            }
            else
            {
                if (parent->right == node)
                {
                    root = rb_rotate_left(parent, root);
                    tmp = parent;
                    parent = node;
                    node = tmp;
                }

                parent->color = BLACK;
                gparent->color = RED;
                root = rb_rotate_right(gparent, root);
            }
        }
        else
        {
            uncle = gparent->left;
            if (uncle && uncle->color == RED)
            {
                uncle->color = BLACK;
                parent->color = BLACK;
                gparent->color = RED;
                node = gparent;
            }
            else
            {
                if (parent->left == node)
                {
                    root = rb_rotate_right(parent, root);
                    tmp = parent;
                    parent = node;
                    node = tmp;
                }

                parent->color = BLACK;
                gparent->color = RED;
                root = rb_rotate_left(gparent, root);
            }
        }
    }

    root->color = BLACK;

    return root;
}

static rb_node_t* rb_erase_rebalance(rb_node_t *node, rb_node_t *parent, rb_node_t *root)
{
    rb_node_t *other, *o_left, *o_right;

    while ((!node || node->color == BLACK) && node != root)
    {
        if (parent->left == node)
        {
            other = parent->right;
            if (other->color == RED)
            {
                other->color = BLACK;
                parent->color = RED;
                root = rb_rotate_left(parent, root);
                other = parent->right;
            }
            if ((!other->left || other->left->color == BLACK) &&
                (!other->right || other->right->color == BLACK))
            {
                other->color = RED;
                node = parent;
                parent = node->parent;
            }
            else
            {
                if (!other->right || other->right->color == BLACK)
                {
                    if ((o_left = other->left))
                    {
                        o_left->color = BLACK;
                    }
                    other->color = RED;
                    root = rb_rotate_right(other, root);
                    other = parent->right;
                }
                other->color = parent->color;
                parent->color = BLACK;
                if (other->right)
                {
                    other->right->color = BLACK;
                }
                root = rb_rotate_left(parent, root);
                node = root;
                break;
            }
        }
        else
        {
            other = parent->left;
            if (other->color == RED)
            {
                other->color = BLACK;
                parent->color = RED;
                root = rb_rotate_right(parent, root);
                other = parent->left;
            }
            if ((!other->left || other->left->color == BLACK) &&
                (!other->right || other->right->color == BLACK))
            {
                other->color = RED;
                node = parent;
                parent = node->parent;
            }
            else
            {
                if (!other->left || other->left->color == BLACK)
                {
                    if ((o_right = other->right))
                    {
                        o_right->color = BLACK;
                    }
                    other->color = RED;
                    root = rb_rotate_left(other, root);
                    other = parent->left;
                }
                other->color = parent->color;
                parent->color = BLACK;
                if (other->left)
                {
                    other->left->color = BLACK;
                }
                root = rb_rotate_right(parent, root);
                node = root;
                break;
            }
        }
    }

    if (node)
    {
        node->color = BLACK;
    }

    return root;
}

static rb_node_t* rb_search_auxiliary(key_t key, rb_node_t* root, rb_node_t** save)
{
    rb_node_t *node = root, *parent = NULL;
    int ret;

    while (node)
    {
        parent = node;
        ret = node->key - key;
        if (0 < ret)
        {
            node = node->left;
        }
        else if (0 > ret)
        {
            node = node->right;
        }
        else
        {
            return node;
        }
    }

    if (save)
    {
        *save = parent;
    }

    return NULL;
}

rb_node_t* rb_insert(key_t key, data_t data, rb_node_t* root)
{
    rb_node_t *parent = NULL, *node;

    parent = NULL;
    if ((node = rb_search_auxiliary(key, root, &parent)))
    {
        return root;
    }

    node = rb_new_node(key, data);
    node->parent = parent;
    node->left = node->right = NULL;
    node->color = RED;

    if (parent)
    {
        if (parent->key > key)
        {
            parent->left = node;
        }
        else
        {
            parent->right = node;
        }
    }
    else
    {
        root = node;
    }

    return rb_insert_rebalance(node, root);
}

rb_node_t* rb_search(key_t key, rb_node_t* root)
{
    return rb_search_auxiliary(key, root, NULL);
}

rb_node_t* rb_erase(key_t key, rb_node_t *root)
{
    rb_node_t *child, *parent, *old, *left, *node;
    color_t color;

    if (!(node = rb_search_auxiliary(key, root, NULL)))
    {
        printf("key %d is not exist!\n");
        return root;
    }

    old = node;

    if (node->left && node->right)
    {
        node = node->right;
        while ((left = node->left) != NULL)
        {
            node = left;
        }
        child = node->right;
        parent = node->parent;
        color = node->color;

        if (child)
        {
            child->parent = parent;
        }
        if (parent)
        {
            if (parent->left == node)
            {
                parent->left = child;
            }
            else
            {
                parent->right = child;
            }
        }
        else
        {
            root = child;
        }

        if (node->parent == old)
        {
            parent = node;
        }

        node->parent = old->parent;
        node->color = old->color;
        node->right = old->right;
        node->left = old->left;

        if (old->parent)
        {
            if (old->parent->left == old)
            {
                old->parent->left = node;
            }
            else
            {
                old->parent->right = node;
            }
        }
        else
        {
            root = node;
        }

        old->left->parent = node;
        if (old->right)
        {
            old->right->parent = node;
        }
    }
    else
    {
        if (!node->left)
        {
            child = node->right;
        }
        else if (!node->right)
        {
            child = node->left;
        }
        parent = node->parent;
        color = node->color;

        if (child)
        {
            child->parent = parent;
        }
        if (parent)
        {
            if (parent->left == node)
            {
                parent->left = child;
            }
            else
            {
                parent->right = child;
            }
        }
        else
        {
            root = child;
        }
    }

    free(old);

    if (color == BLACK)
    {
        root = rb_erase_rebalance(child, parent, root);
    }

    return root;
}





posted on 2008-11-10 17:50 那谁 阅读(13651) 评论(18)  编辑 收藏 引用 所属分类: 算法与数据结构

评论

# re: 红黑树的实现源码(第二次修订版)  回复  更多评论   

我晕倒,有没有优雅一点的,至少短一点的实现?
2008-11-11 15:42 | Wang Feng

# re: 红黑树的实现源码(第二次修订版)  回复  更多评论   

@Wang Feng
楼上的朋友,如果你不满意,大可以自己也去实现一下看看:)
2008-11-11 23:33 |

# re: 红黑树的实现源码(第二次修订版)  回复  更多评论   

写得很艺术
nice
2008-11-12 12:28 | haskell

# re: 红黑树的实现源码(第二次修订版)[未登录]  回复  更多评论   

csdn中的那个也是你发的吧?呵.....
2008-11-18 16:53 | lin

# re: 红黑树的实现源码(第二次修订版)  回复  更多评论   

@lin
CSDN?我不知道这个事情,这个帖子是我在cppblog的原创.
2008-11-19 00:05 |

# re: 红黑树的实现源码(第二次修订版)  回复  更多评论   

搬个凳子慢慢看
2009-01-15 01:02 | linnet

# re: 红黑树的实现源码(第二次修订版)[未登录]  回复  更多评论   

怎麼無法編譯呢?
2009-04-29 03:33 | candy

# re: 红黑树的实现源码(第二次修订版)[未登录]  回复  更多评论   

@candy
你的编译命令是??
我这边直接gcc就行了
2009-04-29 12:49 | 那谁

# re: 红黑树的实现源码(第二次修订版)[未登录]  回复  更多评论   

请高手指教,谢谢。
我将main函数改为,
int main()
{
int i;
key_t key;
rb_node_t* root = NULL, *node = NULL;

while(1)
{
printf("insert: ");
scanf("%d", &key);
if(key <= 0)
break;
if ((root = rb_insert(key, i, root)))
{
printf("[i = %d] insert key %d success!\n", i, key);
}
else
{
printf("[i = %d] insert key %d error!\n", i, key);
exit(-1);
}
}

while(1)
{
printf("delete: ");
scanf("%d", &key);
if(key <= 0)
break;
if ((root = rb_erase(key, root)))
{
printf("[i = %d] erase key %d success\n", i, key);
}
else
{
printf("[i = %d] erase key %d error\n", i, key);
}
}
return 0;
}
编译并运行,
insert: 9
[i = 2] insert key 9 success!
insert: 0
delete: 9
[i = 2] erase key 9 error
delete: 0
请问是什么原因,谢谢。
2010-02-04 16:51 | Jason

# re: 红黑树的实现源码(第二次修订版)  回复  更多评论   

When students want to uderstand about the <a href="http://www.exclusivepapers.com/papers-for-money.php">papers for money</a> they can <a href="http://www.exclusivepapers.com/buy-essay.php">buy essay</a> related to this post. Because the critical essay creating has to be a really important thing.
2010-02-22 15:02 | EllavC

# re: 红黑树的实现源码(第二次修订版)  回复  更多评论   

@EllavC
数依然是有问题的, 将你的测试用例 改为下面的试试
//-------------------
int main()
{
int i, count = 10000;
key_t key;
rb_node_t* root = NULL, *node = NULL;

srand(time(NULL));
for (i = 1; i < count; ++i)
{
key = rand() % count;
if ((root = rb_insert(key, i, root)))
{
printf("[i = %d] insert key %d success!\n", i, key);
}
else
{
printf("[i = %d] insert key %d error!\n", i, key);
exit(-1);
}

if ((node = rb_search(key, root)))
{
if (i != node->data) {
printf("[i = %d] search key %d success! <-- X\n", node->data, node->key);
printf("[i = %d] != [node->data = %d ] <-- [key = %d], [node->key = %d]\n", i, node->data, key, node->key);
}
else
printf("[i = %d] search key %d success!\n", node->data, node->key);
}
else
{
printf("[i = %d] search key %d error!\n", i, key);
exit(-1);
}
if (!(i % 10))
{
if ((root = rb_erase(key, root)))
{
printf("[i = %d] erase key %d success\n", i, key);
}
else
{
printf("[i = %d] erase key %d error\n", i, key);
}
}
}

return 0;
}
//-------------------
//-------------------
// 结果的部分内容
/*
[i = 9984] != [node->data = 6004 ] <-- [key = 5893], [node->key = 5893]
[i = 9985] insert key 4330 success!
[i = 2445] search key 4330 success! <-- X
[i = 9985] != [node->data = 2445 ] <-- [key = 4330], [node->key = 4330]
[i = 9986] insert key 1927 success!
[i = 227] search key 1927 success! <-- X
[i = 9986] != [node->data = 227 ] <-- [key = 1927], [node->key = 1927]
[i = 9987] insert key 7978 success!
[i = 647] search key 7978 success! <-- X
[i = 9987] != [node->data = 647 ] <-- [key = 7978], [node->key = 7978]
[i = 9988] insert key 7759 success!
[i = 4671] search key 7759 success! <-- X
[i = 9988] != [node->data = 4671 ] <-- [key = 7759], [node->key = 7759]
[i = 9989] insert key 1231 success!
[i = 4022] search key 1231 success! <-- X
[i = 9989] != [node->data = 4022 ] <-- [key = 1231], [node->key = 1231]
[i = 9990] insert key 1550 success!
[i = 9990] search key 1550 success!
[i = 9990] erase key 1550 success
[i = 9991] insert key 7396 success!
[i = 7878] search key 7396 success! <-- X
[i = 9991] != [node->data = 7878 ] <-- [key = 7396], [node->key = 7396]
[i = 9992] insert key 5687 success!
[i = 9992] search key 5687 success!
[i = 9993] insert key 1755 success!
[i = 9993] search key 1755 success!
[i = 9994] insert key 9388 success!
[i = 9994] search key 9388 success!
[i = 9995] insert key 8158 success!
[i = 9352] search key 8158 success! <-- X
[i = 9995] != [node->data = 9352 ] <-- [key = 8158], [node->key = 8158]
[i = 9996] insert key 7122 success!
[i = 56] search key 7122 success! <-- X
[i = 9996] != [node->data = 56 ] <-- [key = 7122], [node->key = 7122]
[i = 9997] insert key 6220 success!
[i = 8154] search key 6220 success! <-- X
[i = 9997] != [node->data = 8154 ] <-- [key = 6220], [node->key = 6220]
[i = 9998] insert key 9219 success!
[i = 9998] search key 9219 success!
*/
//---------------
/*
你的测试用例全部正确是因为你没有去判断通过key查到的node里面的内容是否和放入的内容一致,我在此比了一下,问题暴露出来了
*/
2011-07-19 15:46 | rc8523

# re: 红黑树的实现源码(第二次修订版)  回复  更多评论   

@rc8523
<-- X 代表的是有问题的地方
下面一行是节点详细内容
2011-07-19 15:48 | rc8523

# re: 红黑树的实现源码(第二次修订版)  回复  更多评论   

@rc8523
因为rb_insert()了已经存在的key后,并不返回NULL,而是
直接返回root指针,所以rb_search()的返回值在这种情况下
只是上次插入的节点
2012-01-05 14:57 | qman007

# re: 红黑树的实现源码(第二次修订版)  回复  更多评论   

你现在的实现还是有问题吧 好好看看
2012-04-18 09:19 | Apollo Fang

# re: 红黑树的实现源码(第二次修订版)  回复  更多评论   

替换数据不是更好?
2012-04-19 10:26 | Apollo Fang

# re: 红黑树的实现源码(第二次修订版)  回复  更多评论   

也怪我的测试用例写的不好, 仅仅对插入操作进行了测试, 我向所有因为阅读了这份代码而造成困
2012-08-03 19:25 | regalos originales aniversario

# re: 红黑树的实现源码(第二次修订版)  回复  更多评论   

例写的不好, 仅仅对插入操作进行了测试, 我向所有因为阅读了
2012-08-04 15:17 | wholesale kurti

# re: 红黑树的实现源码(第二次修订版)   回复  更多评论   

也怪我的测试用例写的不好, 仅仅对插入操作进行了测试, 我向所有因为阅读了这份代码而造成困
2012-11-27 20:19 | abogados divorcios madrid

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理