紅黑樹——初步剖析

個人理解:紅黑樹就是相當於一個二叉平衡樹。而它的平衡條件也就是下面五條性質:

(1)每個節點要麼是紅的,要麼是黑的。

(2)根節點是黑色的

(3)每個葉節點是黑色的(樹尾端的NIL指針或NULL節點)

(4)如果一個節點是紅色的,那他 的兩個子節點就是黑的

(5)對於任意節點而言,其到葉節點(樹尾端NULL)的每條路徑上都包含相同數目的黑結點。

C++實現紅黑樹:

<red_black _tree.h>

enum RBTColor{RED, BLACK};

template <class T>
class RBTNode{
    public:
        RBTColor color;    // 顏色
        T key;             // 關鍵字(鍵值)
        RBTNode *left;     // 左孩子
        RBTNode *right;    // 右孩子
        RBTNode *parent;   // 父結點

        RBTNode(T value, RBTColor c, RBTNode *p, RBTNode *l, RBTNode *r):
            key(value),color(c),parent(),left(l),right(r) {}
};

template <class T>
class RBTree {
    private:
        RBTNode<T> *mRoot;    // 根結點

    public:
        RBTree();
        ~RBTree();

        // 前序遍歷"紅黑樹"
        void preOrder();
        // 中序遍歷"紅黑樹"
        void inOrder();
        // 後序遍歷"紅黑樹"
        void postOrder();

        // (遞歸實現)查找"紅黑樹"中鍵值爲key的節點
        RBTNode<T>* search(T key);
        // (非遞歸實現)查找"紅黑樹"中鍵值爲key的節點
        RBTNode<T>* iterativeSearch(T key);

        // 查找最小結點:返回最小結點的鍵值。
        T minimum();
        // 查找最大結點:返回最大結點的鍵值。
        T maximum();

        // 找結點(x)的後繼結點。即,查找"紅黑樹中數據值大於該結點"的"最小結點"。
        RBTNode<T>* successor(RBTNode<T> *x);
        // 找結點(x)的前驅結點。即,查找"紅黑樹中數據值小於該結點"的"最大結點"。
        RBTNode<T>* predecessor(RBTNode<T> *x);

        // 將結點(key爲節點鍵值)插入到紅黑樹中
        void insert(T key);

        // 刪除結點(key爲節點鍵值)
        void remove(T key);

        // 銷燬紅黑樹
        void destroy();

        // 打印紅黑樹
        void print();
    private:
        // 前序遍歷"紅黑樹"
        void preOrder(RBTNode<T>* tree) const;
        // 中序遍歷"紅黑樹"
        void inOrder(RBTNode<T>* tree) const;
        // 後序遍歷"紅黑樹"
        void postOrder(RBTNode<T>* tree) const;

        // (遞歸實現)查找"紅黑樹x"中鍵值爲key的節點
        RBTNode<T>* search(RBTNode<T>* x, T key) const;
        // (非遞歸實現)查找"紅黑樹x"中鍵值爲key的節點
        RBTNode<T>* iterativeSearch(RBTNode<T>* x, T key) const;

        // 查找最小結點:返回tree爲根結點的紅黑樹的最小結點。
        RBTNode<T>* minimum(RBTNode<T>* tree);
        // 查找最大結點:返回tree爲根結點的紅黑樹的最大結點。
        RBTNode<T>* maximum(RBTNode<T>* tree);

        // 左旋
        void leftRotate(RBTNode<T>* &root, RBTNode<T>* x);
        // 右旋
        void rightRotate(RBTNode<T>* &root, RBTNode<T>* y);
        // 插入函數
        void insert(RBTNode<T>* &root, RBTNode<T>* node);
        // 插入修正函數
        void insertFixUp(RBTNode<T>* &root, RBTNode<T>* node);
        // 刪除函數
        void remove(RBTNode<T>* &root, RBTNode<T> *node);
        // 刪除修正函數
        void removeFixUp(RBTNode<T>* &root, RBTNode<T> *node, RBTNode<T> *parent);

        // 銷燬紅黑樹
        void destroy(RBTNode<T>* &tree);

        // 打印紅黑樹
        void print(RBTNode<T>* tree, T key, int direction);

#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)
};
//逐個實現,構造,析構,銷燬函數:

 /* 
  * 構造函數
  */
 template <class T>
 RBTree<T>::RBTree():mRoot(NULL)
 {
     mRoot = NULL;
 }
 
 /* 
  * 析構函數
  */
 template <class T>
 RBTree<T>::~RBTree() 
 {
     destroy();
 }
template<class T>
void RBTree<T>::destroy(RBTNode<T>* &tree)
{
     if (tree==NULL)
        return ;
 
     if (tree->left != NULL)
         return destroy(tree->left);
     if (tree->right != NULL)
         return destroy(tree->right);

     delete tree;
     tree=NULL;
}
template<class T>
void RBTree<T>::destory()
{
       destroy(mRoot);
}

/* 
 * 對紅黑樹的節點(x)進行左旋轉
 *
 * 左旋示意圖(對節點x進行左旋):
 *      px                              px
 *     /                               /
 *    x                               y                
 *   /  \      --(左旋)-->           / \                #
 *  lx   y                          x  ry     
 *     /   \                       /  \
 *    ly   ry                     lx  ly  
 *
 *
 */
template <class T>
void RBTree<T>::leftRotate(RBTNode<T>* &root, RBTNode<T>* x)
{
    // 設置x的右孩子爲y
    RBTNode<T> *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)
    {
        root = 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
 * 
 */
template <class T>
void RBTree<T>::rightRotate(RBTNode<T>* &root, RBTNode<T>* y)
{
    // 設置x是當前節點的左孩子。
    RBTNode<T> *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) 
    {
        root = 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 插入的結點        // 對應《算法導論》中的node
 */
template <class T>
void RBTree<T>::insert(RBTNode<T>* &root, RBTNode<T>* node)
{
    RBTNode<T> *y = NULL;
    RBTNode<T> *x = root;

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

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

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

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

/* 
 * 將結點(key爲節點鍵值)插入到紅黑樹中
 *
 * 參數說明:
 *     tree 紅黑樹的根結點
 *     key 插入結點的鍵值
 */
template <class T>
void RBTree<T>::insert(T key)
{
    RBTNode<T> *z=NULL;

    // 如果新建結點失敗,則返回。
    if ((z=new RBTNode<T>(key,BLACK,NULL,NULL,NULL)) == NULL)
        return ;

    insert(mRoot, z);
}


/*
 * 紅黑樹插入修正函數
 *
 * 在向紅黑樹中插入節點之後(失去平衡),再調用該函數;
 * 目的是將它重新塑造成一顆紅黑樹。
 *
 * 參數說明:
 *     root 紅黑樹的根
 *     node 插入的結點        // 對應《算法導論》中的z
 */
template <class T>
void RBTree<T>::insertFixUp(RBTNode<T>* &root, RBTNode<T>* node)
{
    RBTNode<T> *parent, *gparent;

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

        //若“父節點”是“祖父節點的左孩子”
        if (parent == gparent->left)
        {
            // Case 1條件:叔叔節點是紅色
            {
                RBTNode<T> *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)
            {
                RBTNode<T> *tmp;
                leftRotate(root, parent);
                tmp = parent;
                parent = node;
                node = tmp;
            }

            // Case 3條件:叔叔是黑色,且當前節點是左孩子。
            rb_set_black(parent);
            rb_set_red(gparent);
            rightRotate(root, gparent);
        } 
        else//若“z的父節點”是“z的祖父節點的右孩子”
        {
            // Case 1條件:叔叔節點是紅色
            {
                RBTNode<T> *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)
            {
                RBTNode<T> *tmp;
                rightRotate(root, parent);
                tmp = parent;
                parent = node;
                node = tmp;
            }

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

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

/* 
 * 刪除結點(node),並返回被刪除的結點
 *
 * 參數說明:
 *     root 紅黑樹的根結點
 *     node 刪除的結點
 */
template <class T>
void RBTree<T>::remove(RBTNode<T>* &root, RBTNode<T> *node)
{
    RBTNode<T> *child, *parent;
    RBTColor color;

    // 被刪除節點的"左右孩子都不爲空"的情況。
    if ( (node->left!=NULL) && (node->right!=NULL) ) 
    {
        // 被刪節點的後繼節點。(稱爲"取代節點")
        // 用它來取代"被刪節點"的位置,然後再將"被刪節點"去掉。
        RBTNode<T> *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 = 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)
            removeFixUp(root, child, parent);

        delete 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 = child;

    if (color == BLACK)
        removeFixUp(root, child, parent);
    delete node;
}

/* 
 * 刪除紅黑樹中鍵值爲key的節點
 *
 * 參數說明:
 *     tree 紅黑樹的根結點
 */
template <class T>
void RBTree<T>::remove(T key)
{
    RBTNode<T> *node; 

    // 查找key對應的節點(node),找到的話就刪除該節點
    if ((node = search(mRoot, key)) != NULL)
        remove(mRoot, node);
}

/*
 * 紅黑樹刪除修正函數
 *
 * 在從紅黑樹中刪除插入節點之後(紅黑樹失去平衡),再調用該函數;
 * 目的是將它重新塑造成一顆紅黑樹。
 *
 * 參數說明:
 *     root 紅黑樹的根
 *     node 待修正的節點
 */
template <class T>
void RBTree<T>::removeFixUp(RBTNode<T>* &root, RBTNode<T> *node, RBTNode<T> *parent)
{
    RBTNode<T> *other;

    while ((!node || rb_is_black(node)) && node != root)
    {
        if (parent->left == node)
        {
            other = parent->right;
            if (rb_is_red(other))
            {
                // Case 1: x的兄弟w是紅色的  
                rb_set_black(other);
                rb_set_red(parent);
                leftRotate(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);
                    rightRotate(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);
                leftRotate(root, parent);
                node = root;
                break;
            }
        }
        else
        {
            other = parent->left;
            if (rb_is_red(other))
            {
                // Case 1: x的兄弟w是紅色的  
                rb_set_black(other);
                rb_set_red(parent);
                rightRotate(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);
                    leftRotate(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);
                rightRotate(root, parent);
                node = root;
                break;
            }
        }
    }
    if (node)
        rb_set_black(node);
}

三種順序的遍歷函數:

 /*
  * 前序遍歷"紅黑樹"
  */
 template <class T>
 void RBTree<T>::preOrder(RBTNode<T>* tree) const
 {
     if(tree != NULL)
    {
         cout<< tree->key << " " ;
         preOrder(tree->left);
         preOrder(tree->right);
     }
 }
 
 template <class T>
 void RBTree<T>::preOrder() 
 {
     preOrder(mRoot);
 }
 
 /*
  * 中序遍歷"紅黑樹"
  */
 template <class T>
 void RBTree<T>::inOrder(RBTNode<T>* tree) const
 {
     if(tree != NULL)
     {
         inOrder(tree->left);
         cout<< tree->key << " " ;
         inOrder(tree->right);
     }
 }
 
 template <class T>
 void RBTree<T>::inOrder() 
 {
     inOrder(mRoot);
 }
 
 /*
  * 後序遍歷"紅黑樹"
  */
 template <class T>
 void RBTree<T>::postOrder(RBTNode<T>* tree) const
 {
     if(tree != NULL)
     {
         postOrder(tree->left);
         postOrder(tree->right);
         cout<< tree->key << " " ;
     }
 }
 
 template <class T>
 void RBTree<T>::postOrder() 
 {
     postOrder(mRoot);
 }

<main.cpp>

  #include <iostream>
  #include "red_black_tree.h"
  using namespace std;
 
 int main()
 {
     int a[]= {10, 40, 30, 60, 90, 70, 20, 50, 80};
     int check_insert=0;    // "插入"動作的檢測開關(0,關閉;1,打開)
     int check_remove=0;    // "刪除"動作的檢測開關(0,關閉;1,打開)
     int i;
     int ilen = (sizeof(a)) / (sizeof(a[0])) ;
     RBTree<int>* tree=new RBTree<int>();
 
     cout << "== 原始數據: ";
     for(i=0; i<ilen; i++)
         cout << a[i] <<" ";
     cout << endl;
 
     cout << "== 前序遍歷: ";
     tree->preOrder();
 
     cout << "\n== 中序遍歷: ";
     tree->inOrder();
 
     cout << "\n== 後序遍歷: ";
     tree->postOrder();
     cout << endl;
 
     // 銷燬紅黑樹
     tree->destroy();
 
     return 0;
 }







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章