紅黑樹

本文參考http://www.javashuo.com/article/p-zdgwljil-t.htmlhttp://www.javashuo.com/article/p-upnmnouk-b.html兩篇文章進行總結。html

一、基本定義和特性node

定義:R-B Tree,全稱是Red-Black Tree,又稱爲「紅黑樹」,它一種特殊的二叉查找樹。紅黑樹的每一個節點上都有存儲位表示節點的顏色,能夠是紅(Red)或黑(Black)。算法

特性:ide

(1)每一個節點或者是黑色,或者是紅色。
(2)根節點是黑色。
(3)每一個葉子節點(NIL)是黑色。 [注意:這裏葉子節點,是指爲空(NIL或NULL)的葉子節點!]
(4)若是一個節點是紅色的,則它的子節點必須是黑色的。
(5)從一個節點到該節點的子孫節點的全部路徑上包含相同數目的黑節點。函數

注意
(01) 特性(3)中的葉子節點,是隻爲空(NIL或null)的節點。
(02) 特性(5),確保沒有一條路徑會比其餘路徑長出倆倍。於是,紅黑樹是相對是接近平衡的二叉樹。post

示意圖:測試

應用:spa

紅黑樹的應用比較普遍,主要是用它來存儲有序的數據,它的時間複雜度是O(lgn),效率很是之高。
例如,Java集合中的TreeSetTreeMap,C++ STL中的set、map,以及Linux虛擬內存的管理,都是經過紅黑樹去實現的。3d

二、紅黑樹的基本操做(一) 左旋和右旋code

左旋:

/* 
 * 對紅黑樹的節點(x)進行左旋轉
 *
 * 左旋示意圖(對節點x進行左旋):
 *      px                              px
 *     /                               /
 *    x                               y                
 *   /  \      --(左旋)-->           / \                #
 *  lx   y                          x  ry     
 *     /   \                       /  \
 *    ly   ry                     lx  ly  
 *
 *
 */
static void rbtree_left_rotate(RBRoot *root, Node *x)
{
    // 設置x的右孩子爲y
    Node *y = x->right;

    // 將 「y的左孩子」 設爲 「x的右孩子」;
    // 若是y的左孩子非空,將 「x」 設爲 「y的左孩子的父親」
    x->right = y->left;
    if (y->left != NULL)
        y->left->parent = x;

    // 將 「x的父親」 設爲 「y的父親」
    y->parent = x->parent;

    if (x->parent == NULL)
    {
        //tree = y;            // 若是 「x的父親」 是空節點,則將y設爲根節點
        root->node = y;            // 若是 「x的父親」 是空節點,則將y設爲根節點
    }
    else
    {
        if (x->parent->left == x)
            x->parent->left = y;    // 若是 x是它父節點的左孩子,則將y設爲「x的父節點的左孩子」
        else
            x->parent->right = y;    // 若是 x是它父節點的左孩子,則將y設爲「x的父節點的左孩子」
    }
    
    // 將 「x」 設爲 「y的左孩子」
    y->left = x;
    // 將 「x的父節點」 設爲 「y」
    x->parent = y;
}

右旋:

 

/* 
 * 對紅黑樹的節點(y)進行右旋轉
 *
 * 右旋示意圖(對節點y進行左旋):
 *            py                               py
 *           /                                /
 *          y                                x                  
 *         /  \      --(右旋)-->            /  \                     #
 *        x   ry                           lx   y  
 *       / \                                   / \                   #
 *      lx  rx                                rx  ry
 * 
 */
static void rbtree_right_rotate(RBRoot *root, Node *y)
{
    // 設置x是當前節點的左孩子。
    Node *x = y->left;

    // 將 「x的右孩子」 設爲 「y的左孩子」;
    // 若是"x的右孩子"不爲空的話,將 「y」 設爲 「x的右孩子的父親」
    y->left = x->right;
    if (x->right != NULL)
        x->right->parent = y;

    // 將 「y的父親」 設爲 「x的父親」
    x->parent = y->parent;

    if (y->parent == NULL) 
    {
        //tree = x;            // 若是 「y的父親」 是空節點,則將x設爲根節點
        root->node = x;            // 若是 「y的父親」 是空節點,則將x設爲根節點
    }
    else
    {
        if (y == y->parent->right)
            y->parent->right = x;    // 若是 y是它父節點的右孩子,則將x設爲「y的父節點的右孩子」
        else
            y->parent->left = x;    // (y是它父節點的左孩子) 將x設爲「x的父節點的左孩子」
    }

    // 將 「y」 設爲 「x的右孩子」
    x->right = y;

    // 將 「y的父節點」 設爲 「x」
    y->parent = x;
}

三、紅黑樹的基本操做(二) 添加

第一步: 將紅黑樹看成一顆二叉查找樹,將節點插入。
       紅黑樹自己就是一顆二叉查找樹,將節點插入後,該樹仍然是一顆二叉查找樹。也就意味着,樹的鍵值仍然是有序的。此外,不管是左旋仍是右旋,若旋轉以前這棵樹是二叉查找樹,旋轉以後它必定仍是二叉查找樹。這也就意味着,任何的旋轉和從新着色操做,都不會改變它仍然是一顆二叉查找樹的事實。
       好吧?那接下來,咱們就來千方百計的旋轉以及從新着色,使這顆樹從新成爲紅黑樹!

第二步:將插入的節點着色爲"紅色"。
       爲何着色成紅色,而不是黑色呢?爲何呢?在回答以前,咱們須要從新溫習一下紅黑樹的特性:
(1) 每一個節點或者是黑色,或者是紅色。
(2) 根節點是黑色。
(3) 每一個葉子節點是黑色。 [注意:這裏葉子節點,是指爲空的葉子節點!]
(4) 若是一個節點是紅色的,則它的子節點必須是黑色的。
(5) 從一個節點到該節點的子孫節點的全部路徑上包含相同數目的黑節點。
       將插入的節點着色爲紅色,不會違背"特性(5)"!少違背一條特性,就意味着咱們須要處理的狀況越少。接下來,就要努力的讓這棵樹知足其它性質便可;知足了的話,它就又是一顆紅黑樹了。o(∩∩)o...哈哈

第三步: 經過一系列的旋轉或着色等操做,使之從新成爲一顆紅黑樹。
       第二步中,將插入節點着色爲"紅色"以後,不會違背"特性(5)"。那它到底會違背哪些特性呢?
       對於"特性(1)",顯然不會違背了。由於咱們已經將它塗成紅色了。
       對於"特性(2)",顯然也不會違背。在第一步中,咱們是將紅黑樹看成二叉查找樹,而後執行的插入操做。而根據二叉查找數的特色,插入操做不會改變根節點。因此,根節點仍然是黑色。
       對於"特性(3)",顯然不會違背了。這裏的葉子節點是指的空葉子節點,插入非空節點並不會對它們形成影響。
       對於"特性(4)",是有可能違背的!
       那接下來,想辦法使之"知足特性(4)",就能夠將樹從新構形成紅黑樹了。

代碼演示:

第一步和第二步代碼:插入和變色

/*
 * 添加節點:將節點(node)插入到紅黑樹中
 *
 * 參數說明:
 *     root 紅黑樹的根
 *     node 插入的結點        // 對應《算法導論》中的z
 */
static void rbtree_insert(RBRoot *root, Node *node)
{
    Node *y = NULL;
    Node *x = root->node;

    // 1. 將紅黑樹看成一顆二叉查找樹,將節點添加到二叉查找樹中。
    while (x != NULL)
    {
        y = x;
        if (node->key < x->key)
            x = x->left;
        else
            x = x->right;
    }
    rb_parent(node) = y;

    if (y != NULL)
    {
        if (node->key < y->key)
            y->left = node;                // 狀況2:若「node所包含的值」 < 「y所包含的值」,則將node設爲「y的左孩子」
        else
            y->right = node;            // 狀況3:(「node所包含的值」 >= 「y所包含的值」)將node設爲「y的右孩子」 
    }
    else
    {
        root->node = node;                // 狀況1:若y是空節點,則將node設爲根
    }

    // 2. 設置節點的顏色爲紅色
    node->color = RED;

    // 3. 將它從新修正爲一顆二叉查找樹
    rbtree_insert_fixup(root, node);
}

第三步代碼:修正

參照:

/*
 * 紅黑樹插入修正函數
 *
 * 在向紅黑樹中插入節點以後(失去平衡),再調用該函數;
 * 目的是將它從新塑形成一顆紅黑樹。
 *
 * 參數說明:
 *     root 紅黑樹的根
 *     node 插入的結點        // 對應《算法導論》中的z
 */
static void rbtree_insert_fixup(RBRoot *root, Node *node)
{
    Node *parent, *gparent;

    // 若「父節點存在,而且父節點的顏色是紅色」
    while ((parent = rb_parent(node)) && rb_is_red(parent))
    {
        gparent = rb_parent(parent);

        //若「父節點」是「祖父節點的左孩子」
        if (parent == gparent->left)
        {
            // Case 1條件:叔叔節點是紅色
            {
                Node *uncle = gparent->right;
                if (uncle && rb_is_red(uncle))
                {
                    rb_set_black(uncle);
                    rb_set_black(parent);
                    rb_set_red(gparent);
                    node = gparent;
                    continue;
                }
            }

            // Case 2條件:叔叔是黑色,且當前節點是右孩子
            if (parent->right == node)
            {
                Node *tmp;
                rbtree_left_rotate(root, parent);
                tmp = parent;
                parent = node;
                node = tmp;
            }

            // Case 3條件:叔叔是黑色,且當前節點是左孩子。
            rb_set_black(parent);
            rb_set_red(gparent);
            rbtree_right_rotate(root, gparent);
        } 
        else//若「z的父節點」是「z的祖父節點的右孩子」
        {
            // Case 1條件:叔叔節點是紅色
            {
                Node *uncle = gparent->left;
                if (uncle && rb_is_red(uncle))
                {
                    rb_set_black(uncle);
                    rb_set_black(parent);
                    rb_set_red(gparent);
                    node = gparent;
                    continue;
                }
            }

            // Case 2條件:叔叔是黑色,且當前節點是左孩子
            if (parent->left == node)
            {
                Node *tmp;
                rbtree_right_rotate(root, parent);
                tmp = parent;
                parent = node;
                node = tmp;
            }

            // Case 3條件:叔叔是黑色,且當前節點是右孩子。
            rb_set_black(parent);
            rb_set_red(gparent);
            rbtree_left_rotate(root, gparent);
        }
    }

    // 將根節點設爲黑色
    rb_set_black(root->node);
}

四、紅黑樹的基本操做(三) 刪除

將紅黑樹內的某一個節點刪除。須要執行的操做依次是:首先,將紅黑樹看成一顆二叉查找樹,將該節點從二叉查找樹中刪除;而後,經過"旋轉和從新着色"等一系列來修正該樹,使之從新成爲一棵紅黑樹。詳細描述以下:

第一步:將紅黑樹看成一顆二叉查找樹,將節點刪除。
       這和"刪除常規二叉查找樹中刪除節點的方法是同樣的"。分3種狀況:
       ① 被刪除節點沒有兒子,即爲葉節點。那麼,直接將該節點刪除就OK了。
       ② 被刪除節點只有一個兒子。那麼,直接刪除該節點,並用該節點的惟一子節點頂替它的位置。
       ③ 被刪除節點有兩個兒子。那麼,先找出它的後繼節點;而後把「它的後繼節點的內容」複製給「該節點的內容」;以後,刪除「它的後繼節點」。在這裏,後繼節點至關於替身,在將後繼節點的內容複製給"被刪除節點"以後,再將後繼節點刪除。這樣就巧妙的將問題轉換爲"刪除後繼節點"的狀況了,下面就考慮後繼節點。 在"被刪除節點"有兩個非空子節點的狀況下,它的後繼不多是雙子非空。既然"的後繼節點"不可能雙子都非空,就意味着"該節點的後繼節點"要麼沒有兒子,要麼只有一個兒子。若沒有兒子,則按"狀況① "進行處理;若只有一個兒子,則按"狀況② "進行處理。

第二步:經過"旋轉和從新着色"等一系列來修正該樹,使之從新成爲一棵紅黑樹。
       由於"第一步"中刪除節點以後,可能會違背紅黑樹的特性。因此須要經過"旋轉和從新着色"來修正該樹,使之從新成爲一棵紅黑樹。

代碼演示:

第一步代碼:節點刪除

/* 
 * 刪除結點
 *
 * 參數說明:
 *     tree 紅黑樹的根結點
 *     node 刪除的結點
 */
void rbtree_delete(RBRoot *root, Node *node)
{
    Node *child, *parent;
    int color;

    // 被刪除節點的"左右孩子都不爲空"的狀況。
    if ( (node->left!=NULL) && (node->right!=NULL) ) 
    {
        // 被刪節點的後繼節點。(稱爲"取代節點")
        // 用它來取代"被刪節點"的位置,而後再將"被刪節點"去掉。
        Node *replace = node;

        // 獲取後繼節點
        replace = replace->right;
        while (replace->left != NULL)
            replace = replace->left;

        // "node節點"不是根節點(只有根節點不存在父節點)
        if (rb_parent(node))
        {
            if (rb_parent(node)->left == node)
                rb_parent(node)->left = replace;
            else
                rb_parent(node)->right = replace;
        } 
        else 
            // "node節點"是根節點,更新根節點。
            root->node = replace;

        // child是"取代節點"的右孩子,也是須要"調整的節點"。
        // "取代節點"確定不存在左孩子!由於它是一個後繼節點。
        child = replace->right;
        parent = rb_parent(replace);
        // 保存"取代節點"的顏色
        color = rb_color(replace);

        // "被刪除節點"是"它的後繼節點的父節點"
        if (parent == node)
        {
            parent = replace;
        } 
        else
        {
            // child不爲空
            if (child)
                rb_set_parent(child, parent);
            parent->left = child;

            replace->right = node->right;
            rb_set_parent(node->right, replace);
        }

        replace->parent = node->parent;
        replace->color = node->color;
        replace->left = node->left;
        node->left->parent = replace;

        if (color == BLACK)
            rbtree_delete_fixup(root, child, parent);
        free(node);

        return ;
    }

    if (node->left !=NULL)
        child = node->left;
    else 
        child = node->right;

    parent = node->parent;
    // 保存"取代節點"的顏色
    color = node->color;

    if (child)
        child->parent = parent;

    // "node節點"不是根節點
    if (parent)
    {
        if (parent->left == node)
            parent->left = child;
        else
            parent->right = child;
    }
    else
        root->node = child;

    if (color == BLACK)
        rbtree_delete_fixup(root, child, parent);
    free(node);
}

第二步代碼:刪除修正

圖示:

/*
 * 紅黑樹刪除修正函數
 *
 * 在從紅黑樹中刪除插入節點以後(紅黑樹失去平衡),再調用該函數;
 * 目的是將它從新塑形成一顆紅黑樹。
 *
 * 參數說明:
 *     root 紅黑樹的根
 *     node 待修正的節點
 */
static void rbtree_delete_fixup(RBRoot *root, Node *node, Node *parent)
{
    Node *other;

    while ((!node || rb_is_black(node)) && node != root->node)
    {
        if (parent->left == node)
        {
            other = parent->right;
            if (rb_is_red(other))
            {
                // Case 1: x的兄弟w是紅色的  
                rb_set_black(other);
                rb_set_red(parent);
                rbtree_left_rotate(root, parent);
                other = parent->right;
            }
            if ((!other->left || rb_is_black(other->left)) &&
                (!other->right || rb_is_black(other->right)))
            {
                // Case 2: x的兄弟w是黑色,且w的倆個孩子也都是黑色的  
                rb_set_red(other);
                node = parent;
                parent = rb_parent(node);
            }
            else
            {
                if (!other->right || rb_is_black(other->right))
                {
                    // Case 3: x的兄弟w是黑色的,而且w的左孩子是紅色,右孩子爲黑色。  
                    rb_set_black(other->left);
                    rb_set_red(other);
                    rbtree_right_rotate(root, other);
                    other = parent->right;
                }
                // Case 4: x的兄弟w是黑色的;而且w的右孩子是紅色的,左孩子任意顏色。
                rb_set_color(other, rb_color(parent));
                rb_set_black(parent);
                rb_set_black(other->right);
                rbtree_left_rotate(root, parent);
                node = root->node;
                break;
            }
        }
        else
        {
            other = parent->left;
            if (rb_is_red(other))
            {
                // Case 1: x的兄弟w是紅色的  
                rb_set_black(other);
                rb_set_red(parent);
                rbtree_right_rotate(root, parent);
                other = parent->left;
            }
            if ((!other->left || rb_is_black(other->left)) &&
                (!other->right || rb_is_black(other->right)))
            {
                // Case 2: x的兄弟w是黑色,且w的倆個孩子也都是黑色的  
                rb_set_red(other);
                node = parent;
                parent = rb_parent(node);
            }
            else
            {
                if (!other->left || rb_is_black(other->left))
                {
                    // Case 3: x的兄弟w是黑色的,而且w的左孩子是紅色,右孩子爲黑色。  
                    rb_set_black(other->right);
                    rb_set_red(other);
                    rbtree_left_rotate(root, other);
                    other = parent->left;
                }
                // Case 4: x的兄弟w是黑色的;而且w的右孩子是紅色的,左孩子任意顏色。
                rb_set_color(other, rb_color(parent));
                rb_set_black(parent);
                rb_set_black(other->left);
                rbtree_right_rotate(root, parent);
                node = root->node;
                break;
            }
        }
    }
    if (node)
        rb_set_black(node);
}

 源碼:

紅黑樹的實現文件(rbtree.h)

#ifndef _RED_BLACK_TREE_H_
#define _RED_BLACK_TREE_H_

#define RED        0    // 紅色節點
#define BLACK    1    // 黑色節點

typedef int Type;

// 紅黑樹的節點
typedef struct RBTreeNode{
    unsigned char color;        // 顏色(RED 或 BLACK)
    Type   key;                    // 關鍵字(鍵值)
    struct RBTreeNode *left;    // 左孩子
    struct RBTreeNode *right;    // 右孩子
    struct RBTreeNode *parent;    // 父結點
}Node, *RBTree;

// 紅黑樹的根
typedef struct rb_root{
    Node *node;
}RBRoot;

// 建立紅黑樹,返回"紅黑樹的根"!
RBRoot* create_rbtree();

// 銷燬紅黑樹
void destroy_rbtree(RBRoot *root);

// 將結點插入到紅黑樹中。插入成功,返回0;失敗返回-1。
int insert_rbtree(RBRoot *root, Type key);

// 刪除結點(key爲節點的值)
void delete_rbtree(RBRoot *root, Type key);


// 前序遍歷"紅黑樹"
void preorder_rbtree(RBRoot *root);
// 中序遍歷"紅黑樹"
void inorder_rbtree(RBRoot *root);
// 後序遍歷"紅黑樹"
void postorder_rbtree(RBRoot *root);

// (遞歸實現)查找"紅黑樹"中鍵值爲key的節點。找到的話,返回0;不然,返回-1。
int rbtree_search(RBRoot *root, Type key);
// (非遞歸實現)查找"紅黑樹"中鍵值爲key的節點。找到的話,返回0;不然,返回-1。
int iterative_rbtree_search(RBRoot *root, Type key);

// 返回最小結點的值(將值保存到val中)。找到的話,返回0;不然返回-1。
int rbtree_minimum(RBRoot *root, int *val);
// 返回最大結點的值(將值保存到val中)。找到的話,返回0;不然返回-1。
int rbtree_maximum(RBRoot *root, int *val);

// 打印紅黑樹
void print_rbtree(RBRoot *root);

#endif
View Code

紅黑樹的實現文件(rbtree.c)

/**
 * C語言實現的紅黑樹(Red Black Tree)
 *
 * @author skywang
 * @date 2013/11/18
 */

#include <stdio.h>
#include <stdlib.h>
#include "rbtree.h"

#define rb_parent(r)   ((r)->parent)
#define rb_color(r) ((r)->color)
#define rb_is_red(r)   ((r)->color==RED)
#define rb_is_black(r)  ((r)->color==BLACK)
#define rb_set_black(r)  do { (r)->color = BLACK; } while (0)
#define rb_set_red(r)  do { (r)->color = RED; } while (0)
#define rb_set_parent(r,p)  do { (r)->parent = (p); } while (0)
#define rb_set_color(r,c)  do { (r)->color = (c); } while (0)

/*
 * 建立紅黑樹,返回"紅黑樹的根"!
 */
RBRoot* create_rbtree()
{
    RBRoot *root = (RBRoot *)malloc(sizeof(RBRoot));
    root->node = NULL;

    return root;
}

/*
 * 前序遍歷"紅黑樹"
 */
static void preorder(RBTree tree)
{
    if(tree != NULL)
    {
        printf("%d ", tree->key);
        preorder(tree->left);
        preorder(tree->right);
    }
}
void preorder_rbtree(RBRoot *root) 
{
    if (root)
        preorder(root->node);
}

/*
 * 中序遍歷"紅黑樹"
 */
static void inorder(RBTree tree)
{
    if(tree != NULL)
    {
        inorder(tree->left);
        printf("%d ", tree->key);
        inorder(tree->right);
    }
}

void inorder_rbtree(RBRoot *root) 
{
    if (root)
        inorder(root->node);
}

/*
 * 後序遍歷"紅黑樹"
 */
static void postorder(RBTree tree)
{
    if(tree != NULL)
    {
        postorder(tree->left);
        postorder(tree->right);
        printf("%d ", tree->key);
    }
}

void postorder_rbtree(RBRoot *root)
{
    if (root)
        postorder(root->node);
}

/*
 * (遞歸實現)查找"紅黑樹x"中鍵值爲key的節點
 */
static Node* search(RBTree x, Type key)
{
    if (x==NULL || x->key==key)
        return x;

    if (key < x->key)
        return search(x->left, key);
    else
        return search(x->right, key);
}
int rbtree_search(RBRoot *root, Type key)
{
    if (root)
        return search(root->node, key)? 0 : -1;
}

/*
 * (非遞歸實現)查找"紅黑樹x"中鍵值爲key的節點
 */
static Node* iterative_search(RBTree x, Type key)
{
    while ((x!=NULL) && (x->key!=key))
    {
        if (key < x->key)
            x = x->left;
        else
            x = x->right;
    }

    return x;
}
int iterative_rbtree_search(RBRoot *root, Type key)
{
    if (root)
        return iterative_search(root->node, key) ? 0 : -1;
}

/* 
 * 查找最小結點:返回tree爲根結點的紅黑樹的最小結點。
 */
static Node* minimum(RBTree tree)
{
    if (tree == NULL)
        return NULL;

    while(tree->left != NULL)
        tree = tree->left;
    return tree;
}

int rbtree_minimum(RBRoot *root, int *val)
{
    Node *node;

    if (root)
        node = minimum(root->node);

    if (node == NULL)
        return -1;

    *val = node->key;
    return 0;
}
 
/* 
 * 查找最大結點:返回tree爲根結點的紅黑樹的最大結點。
 */
static Node* maximum(RBTree tree)
{
    if (tree == NULL)
        return NULL;

    while(tree->right != NULL)
        tree = tree->right;
    return tree;
}

int rbtree_maximum(RBRoot *root, int *val)
{
    Node *node;

    if (root)
        node = maximum(root->node);

    if (node == NULL)
        return -1;

    *val = node->key;
    return 0;
}

/* 
 * 找結點(x)的後繼結點。即,查找"紅黑樹中數據值大於該結點"的"最小結點"。
 */
static Node* rbtree_successor(RBTree x)
{
    // 若是x存在右孩子,則"x的後繼結點"爲 "以其右孩子爲根的子樹的最小結點"。
    if (x->right != NULL)
        return minimum(x->right);

    // 若是x沒有右孩子。則x有如下兩種可能:
    // (01) x是"一個左孩子",則"x的後繼結點"爲 "它的父結點"。
    // (02) x是"一個右孩子",則查找"x的最低的父結點,而且該父結點要具備左孩子",找到的這個"最低的父結點"就是"x的後繼結點"。
    Node* y = x->parent;
    while ((y!=NULL) && (x==y->right))
    {
        x = y;
        y = y->parent;
    }

    return y;
}
 
/* 
 * 找結點(x)的前驅結點。即,查找"紅黑樹中數據值小於該結點"的"最大結點"。
 */
static Node* rbtree_predecessor(RBTree x)
{
    // 若是x存在左孩子,則"x的前驅結點"爲 "以其左孩子爲根的子樹的最大結點"。
    if (x->left != NULL)
        return maximum(x->left);

    // 若是x沒有左孩子。則x有如下兩種可能:
    // (01) x是"一個右孩子",則"x的前驅結點"爲 "它的父結點"。
    // (01) x是"一個左孩子",則查找"x的最低的父結點,而且該父結點要具備右孩子",找到的這個"最低的父結點"就是"x的前驅結點"。
    Node* y = x->parent;
    while ((y!=NULL) && (x==y->left))
    {
        x = y;
        y = y->parent;
    }

    return y;
}

/* 
 * 對紅黑樹的節點(x)進行左旋轉
 *
 * 左旋示意圖(對節點x進行左旋):
 *      px                              px
 *     /                               /
 *    x                               y                
 *   /  \      --(左旋)-->           / \                #
 *  lx   y                          x  ry     
 *     /   \                       /  \
 *    ly   ry                     lx  ly  
 *
 *
 */
static void rbtree_left_rotate(RBRoot *root, Node *x)
{
    // 設置x的右孩子爲y
    Node *y = x->right;

    // 將 「y的左孩子」 設爲 「x的右孩子」;
    // 若是y的左孩子非空,將 「x」 設爲 「y的左孩子的父親」
    x->right = y->left;
    if (y->left != NULL)
        y->left->parent = x;

    // 將 「x的父親」 設爲 「y的父親」
    y->parent = x->parent;

    if (x->parent == NULL)
    {
        //tree = y;            // 若是 「x的父親」 是空節點,則將y設爲根節點
        root->node = y;            // 若是 「x的父親」 是空節點,則將y設爲根節點
    }
    else
    {
        if (x->parent->left == x)
            x->parent->left = y;    // 若是 x是它父節點的左孩子,則將y設爲「x的父節點的左孩子」
        else
            x->parent->right = y;    // 若是 x是它父節點的左孩子,則將y設爲「x的父節點的左孩子」
    }
    
    // 將 「x」 設爲 「y的左孩子」
    y->left = x;
    // 將 「x的父節點」 設爲 「y」
    x->parent = y;
}

/* 
 * 對紅黑樹的節點(y)進行右旋轉
 *
 * 右旋示意圖(對節點y進行左旋):
 *            py                               py
 *           /                                /
 *          y                                x                  
 *         /  \      --(右旋)-->            /  \                     #
 *        x   ry                           lx   y  
 *       / \                                   / \                   #
 *      lx  rx                                rx  ry
 * 
 */
static void rbtree_right_rotate(RBRoot *root, Node *y)
{
    // 設置x是當前節點的左孩子。
    Node *x = y->left;

    // 將 「x的右孩子」 設爲 「y的左孩子」;
    // 若是"x的右孩子"不爲空的話,將 「y」 設爲 「x的右孩子的父親」
    y->left = x->right;
    if (x->right != NULL)
        x->right->parent = y;

    // 將 「y的父親」 設爲 「x的父親」
    x->parent = y->parent;

    if (y->parent == NULL) 
    {
        //tree = x;            // 若是 「y的父親」 是空節點,則將x設爲根節點
        root->node = x;            // 若是 「y的父親」 是空節點,則將x設爲根節點
    }
    else
    {
        if (y == y->parent->right)
            y->parent->right = x;    // 若是 y是它父節點的右孩子,則將x設爲「y的父節點的右孩子」
        else
            y->parent->left = x;    // (y是它父節點的左孩子) 將x設爲「x的父節點的左孩子」
    }

    // 將 「y」 設爲 「x的右孩子」
    x->right = y;

    // 將 「y的父節點」 設爲 「x」
    y->parent = x;
}

/*
 * 紅黑樹插入修正函數
 *
 * 在向紅黑樹中插入節點以後(失去平衡),再調用該函數;
 * 目的是將它從新塑形成一顆紅黑樹。
 *
 * 參數說明:
 *     root 紅黑樹的根
 *     node 插入的結點        // 對應《算法導論》中的z
 */
static void rbtree_insert_fixup(RBRoot *root, Node *node)
{
    Node *parent, *gparent;

    // 若「父節點存在,而且父節點的顏色是紅色」
    while ((parent = rb_parent(node)) && rb_is_red(parent))
    {
        gparent = rb_parent(parent);

        //若「父節點」是「祖父節點的左孩子」
        if (parent == gparent->left)
        {
            // Case 1條件:叔叔節點是紅色
            {
                Node *uncle = gparent->right;
                if (uncle && rb_is_red(uncle))
                {
                    rb_set_black(uncle);
                    rb_set_black(parent);
                    rb_set_red(gparent);
                    node = gparent;
                    continue;
                }
            }

            // Case 2條件:叔叔是黑色,且當前節點是右孩子
            if (parent->right == node)
            {
                Node *tmp;
                rbtree_left_rotate(root, parent);
                tmp = parent;
                parent = node;
                node = tmp;
            }

            // Case 3條件:叔叔是黑色,且當前節點是左孩子。
            rb_set_black(parent);
            rb_set_red(gparent);
            rbtree_right_rotate(root, gparent);
        } 
        else//若「z的父節點」是「z的祖父節點的右孩子」
        {
            // Case 1條件:叔叔節點是紅色
            {
                Node *uncle = gparent->left;
                if (uncle && rb_is_red(uncle))
                {
                    rb_set_black(uncle);
                    rb_set_black(parent);
                    rb_set_red(gparent);
                    node = gparent;
                    continue;
                }
            }

            // Case 2條件:叔叔是黑色,且當前節點是左孩子
            if (parent->left == node)
            {
                Node *tmp;
                rbtree_right_rotate(root, parent);
                tmp = parent;
                parent = node;
                node = tmp;
            }

            // Case 3條件:叔叔是黑色,且當前節點是右孩子。
            rb_set_black(parent);
            rb_set_red(gparent);
            rbtree_left_rotate(root, gparent);
        }
    }

    // 將根節點設爲黑色
    rb_set_black(root->node);
}

/*
 * 添加節點:將節點(node)插入到紅黑樹中
 *
 * 參數說明:
 *     root 紅黑樹的根
 *     node 插入的結點        // 對應《算法導論》中的z
 */
static void rbtree_insert(RBRoot *root, Node *node)
{
    Node *y = NULL;
    Node *x = root->node;

    // 1. 將紅黑樹看成一顆二叉查找樹,將節點添加到二叉查找樹中。
    while (x != NULL)
    {
        y = x;
        if (node->key < x->key)
            x = x->left;
        else
            x = x->right;
    }
    rb_parent(node) = y;

    if (y != NULL)
    {
        if (node->key < y->key)
            y->left = node;                // 狀況2:若「node所包含的值」 < 「y所包含的值」,則將node設爲「y的左孩子」
        else
            y->right = node;            // 狀況3:(「node所包含的值」 >= 「y所包含的值」)將node設爲「y的右孩子」 
    }
    else
    {
        root->node = node;                // 狀況1:若y是空節點,則將node設爲根
    }

    // 2. 設置節點的顏色爲紅色
    node->color = RED;

    // 3. 將它從新修正爲一顆二叉查找樹
    rbtree_insert_fixup(root, node);
}

/*
 * 建立結點
 *
 * 參數說明:
 *     key 是鍵值。
 *     parent 是父結點。
 *     left 是左孩子。
 *     right 是右孩子。
 */
static Node* create_rbtree_node(Type key, Node *parent, Node *left, Node* right)
{
    Node* p;

    if ((p = (Node *)malloc(sizeof(Node))) == NULL)
        return NULL;
    p->key = key;
    p->left = left;
    p->right = right;
    p->parent = parent;
    p->color = BLACK; // 默認爲黑色

    return p;
}

/* 
 * 新建結點(節點鍵值爲key),並將其插入到紅黑樹中
 *
 * 參數說明:
 *     root 紅黑樹的根
 *     key 插入結點的鍵值
 * 返回值:
 *     0,插入成功
 *     -1,插入失敗
 */
int insert_rbtree(RBRoot *root, Type key)
{
    Node *node;    // 新建結點

    // 不容許插入相同鍵值的節點。
    // (若想容許插入相同鍵值的節點,註釋掉下面兩句話便可!)
    if (search(root->node, key) != NULL)
        return -1;

    // 若是新建結點失敗,則返回。
    if ((node=create_rbtree_node(key, NULL, NULL, NULL)) == NULL)
        return -1;

    rbtree_insert(root, node);

    return 0;
}

/*
 * 紅黑樹刪除修正函數
 *
 * 在從紅黑樹中刪除插入節點以後(紅黑樹失去平衡),再調用該函數;
 * 目的是將它從新塑形成一顆紅黑樹。
 *
 * 參數說明:
 *     root 紅黑樹的根
 *     node 待修正的節點
 */
static void rbtree_delete_fixup(RBRoot *root, Node *node, Node *parent)
{
    Node *other;

    while ((!node || rb_is_black(node)) && node != root->node)
    {
        if (parent->left == node)
        {
            other = parent->right;
            if (rb_is_red(other))
            {
                // Case 1: x的兄弟w是紅色的  
                rb_set_black(other);
                rb_set_red(parent);
                rbtree_left_rotate(root, parent);
                other = parent->right;
            }
            if ((!other->left || rb_is_black(other->left)) &&
                (!other->right || rb_is_black(other->right)))
            {
                // Case 2: x的兄弟w是黑色,且w的倆個孩子也都是黑色的  
                rb_set_red(other);
                node = parent;
                parent = rb_parent(node);
            }
            else
            {
                if (!other->right || rb_is_black(other->right))
                {
                    // Case 3: x的兄弟w是黑色的,而且w的左孩子是紅色,右孩子爲黑色。  
                    rb_set_black(other->left);
                    rb_set_red(other);
                    rbtree_right_rotate(root, other);
                    other = parent->right;
                }
                // Case 4: x的兄弟w是黑色的;而且w的右孩子是紅色的,左孩子任意顏色。
                rb_set_color(other, rb_color(parent));
                rb_set_black(parent);
                rb_set_black(other->right);
                rbtree_left_rotate(root, parent);
                node = root->node;
                break;
            }
        }
        else
        {
            other = parent->left;
            if (rb_is_red(other))
            {
                // Case 1: x的兄弟w是紅色的  
                rb_set_black(other);
                rb_set_red(parent);
                rbtree_right_rotate(root, parent);
                other = parent->left;
            }
            if ((!other->left || rb_is_black(other->left)) &&
                (!other->right || rb_is_black(other->right)))
            {
                // Case 2: x的兄弟w是黑色,且w的倆個孩子也都是黑色的  
                rb_set_red(other);
                node = parent;
                parent = rb_parent(node);
            }
            else
            {
                if (!other->left || rb_is_black(other->left))
                {
                    // Case 3: x的兄弟w是黑色的,而且w的左孩子是紅色,右孩子爲黑色。  
                    rb_set_black(other->right);
                    rb_set_red(other);
                    rbtree_left_rotate(root, other);
                    other = parent->left;
                }
                // Case 4: x的兄弟w是黑色的;而且w的右孩子是紅色的,左孩子任意顏色。
                rb_set_color(other, rb_color(parent));
                rb_set_black(parent);
                rb_set_black(other->left);
                rbtree_right_rotate(root, parent);
                node = root->node;
                break;
            }
        }
    }
    if (node)
        rb_set_black(node);
}

/* 
 * 刪除結點
 *
 * 參數說明:
 *     tree 紅黑樹的根結點
 *     node 刪除的結點
 */
void rbtree_delete(RBRoot *root, Node *node)
{
    Node *child, *parent;
    int color;

    // 被刪除節點的"左右孩子都不爲空"的狀況。
    if ( (node->left!=NULL) && (node->right!=NULL) ) 
    {
        // 被刪節點的後繼節點。(稱爲"取代節點")
        // 用它來取代"被刪節點"的位置,而後再將"被刪節點"去掉。
        Node *replace = node;

        // 獲取後繼節點
        replace = replace->right;
        while (replace->left != NULL)
            replace = replace->left;

        // "node節點"不是根節點(只有根節點不存在父節點)
        if (rb_parent(node))
        {
            if (rb_parent(node)->left == node)
                rb_parent(node)->left = replace;
            else
                rb_parent(node)->right = replace;
        } 
        else 
            // "node節點"是根節點,更新根節點。
            root->node = replace;

        // child是"取代節點"的右孩子,也是須要"調整的節點"。
        // "取代節點"確定不存在左孩子!由於它是一個後繼節點。
        child = replace->right;
        parent = rb_parent(replace);
        // 保存"取代節點"的顏色
        color = rb_color(replace);

        // "被刪除節點"是"它的後繼節點的父節點"
        if (parent == node)
        {
            parent = replace;
        } 
        else
        {
            // child不爲空
            if (child)
                rb_set_parent(child, parent);
            parent->left = child;

            replace->right = node->right;
            rb_set_parent(node->right, replace);
        }

        replace->parent = node->parent;
        replace->color = node->color;
        replace->left = node->left;
        node->left->parent = replace;

        if (color == BLACK)
            rbtree_delete_fixup(root, child, parent);
        free(node);

        return ;
    }

    if (node->left !=NULL)
        child = node->left;
    else 
        child = node->right;

    parent = node->parent;
    // 保存"取代節點"的顏色
    color = node->color;

    if (child)
        child->parent = parent;

    // "node節點"不是根節點
    if (parent)
    {
        if (parent->left == node)
            parent->left = child;
        else
            parent->right = child;
    }
    else
        root->node = child;

    if (color == BLACK)
        rbtree_delete_fixup(root, child, parent);
    free(node);
}

/* 
 * 刪除鍵值爲key的結點
 *
 * 參數說明:
 *     tree 紅黑樹的根結點
 *     key 鍵值
 */
void delete_rbtree(RBRoot *root, Type key)
{
    Node *z, *node; 

    if ((z = search(root->node, key)) != NULL)
        rbtree_delete(root, z);
}

/*
 * 銷燬紅黑樹
 */
static void rbtree_destroy(RBTree tree)
{
    if (tree==NULL)
        return ;

    if (tree->left != NULL)
        rbtree_destroy(tree->left);
    if (tree->right != NULL)
        rbtree_destroy(tree->right);

    free(tree);
}

void destroy_rbtree(RBRoot *root)
{
    if (root != NULL)
        rbtree_destroy(root->node);

    free(root);
}

/*
 * 打印"紅黑樹"
 *
 * tree       -- 紅黑樹的節點
 * key        -- 節點的鍵值 
 * direction  --  0,表示該節點是根節點;
 *               -1,表示該節點是它的父結點的左孩子;
 *                1,表示該節點是它的父結點的右孩子。
 */
static void rbtree_print(RBTree tree, Type key, int direction)
{
    if(tree != NULL)
    {
        if(direction==0)    // tree是根節點
            printf("%2d(B) is root\n", tree->key);
        else                // tree是分支節點
            printf("%2d(%s) is %2d's %6s child\n", tree->key, rb_is_red(tree)?"R":"B", key, direction==1?"right" : "left");

        rbtree_print(tree->left, tree->key, -1);
        rbtree_print(tree->right,tree->key,  1);
    }
}

void print_rbtree(RBRoot *root)
{
    if (root!=NULL && root->node!=NULL)
        rbtree_print(root->node, root->node->key, 0);
}
View Code

紅黑樹的測試文件(rbtree_test.c)

/**
 * C語言實現的紅黑樹(Red Black Tree)
 *
 * @author skywang
 * @date 2013/11/18
 */

#include <stdio.h>
#include "rbtree.h"

#define CHECK_INSERT 0    // "插入"動做的檢測開關(0,關閉;1,打開)
#define CHECK_DELETE 0    // "刪除"動做的檢測開關(0,關閉;1,打開)
#define LENGTH(a) ( (sizeof(a)) / (sizeof(a[0])) )

void main()
{
    int a[] = {10, 40, 30, 60, 90, 70, 20, 50, 80};
    int i, ilen=LENGTH(a);
    RBRoot *root=NULL;

    root = create_rbtree();
    printf("== 原始數據: ");
    for(i=0; i<ilen; i++)
        printf("%d ", a[i]);
    printf("\n");

    for(i=0; i<ilen; i++)
    {
        insert_rbtree(root, a[i]);
#if CHECK_INSERT
        printf("== 添加節點: %d\n", a[i]);
        printf("== 樹的詳細信息: \n");
        print_rbtree(root);
        printf("\n");
#endif
    }

    printf("== 前序遍歷: ");
    preorder_rbtree(root);

    printf("\n== 中序遍歷: ");
    inorder_rbtree(root);

    printf("\n== 後序遍歷: ");
    postorder_rbtree(root);
    printf("\n");

    if (rbtree_minimum(root, &i)==0)
        printf("== 最小值: %d\n", i);
    if (rbtree_maximum(root, &i)==0)
        printf("== 最大值: %d\n", i);
    printf("== 樹的詳細信息: \n");
    print_rbtree(root);
    printf("\n");

#if CHECK_DELETE
    for(i=0; i<ilen; i++)
    {
        delete_rbtree(root, a[i]);

        printf("== 刪除節點: %d\n", a[i]);
        if (root)
        {
            printf("== 樹的詳細信息: \n");
            print_rbtree(root);
            printf("\n");
        }
    }
#endif

    destroy_rbtree(root);
}
View Code
相關文章
相關標籤/搜索