集合框架知識系列06 HashMap和TreeMap中的紅黑樹

在上一節中,HashMap在jdk 1.8中用了鏈表和紅黑樹兩種方式解決衝突,在TreeMap中也是用紅黑樹存儲的。下面分析一下紅黑樹的結構和基本操做。

1、紅黑樹的特徵和基本操做

上一節中已經描述了紅黑樹的基本概念和特徵,下面直接經過一個例子分析紅黑樹的構造和調整方法。

一、紅黑樹的數據結構

紅黑樹是一棵二叉查找樹,在二叉樹的基礎上增長了節點的顏色,下面是TreeMap中的紅黑樹定義:
private static final boolean RED   = false;
private static final boolean BLACK = true;
static final class Entry<K,V> implements Map.Entry<K,V> {
        K key;
        V value;
        Entry<K,V> left;
        Entry<K,V> right;
        Entry<K,V> parent;
        boolean color = BLACK;

        /**
         * 給定key、value和父節點,構造一個新的。其中節點顏色爲黑色
         */
        Entry(K key, V value, Entry<K,V> parent) {
            this.key = key;
            this.value = value;
            this.parent = parent;
        }
}

二、紅黑樹的左旋和右旋

紅黑樹的插入和刪除,都有可能破壞其特性,就不是一棵紅黑樹了,因此要調整。調整的方法又兩種,一種是改變某個節點的顏色,另一種是結構調整,包括左旋和右旋。
左旋:將X的節點的右兒子節點Y變爲其父節點,而且將Y的左子樹變爲X的右子樹,變換過程入下圖

clipboard.png

右旋:將X的節點的左兒子節點Y變爲其父節點,而且將Y的右子樹變爲X的左子樹,變換過程入下圖

clipboard.png

三、插入節點後調整紅黑樹

當在紅黑樹中插入一個節點後,可能會破壞紅黑樹的規則,首先再回顧一下紅黑數的特色:node

  • 節點是紅色或黑色。
  • 根節點是黑色。
  • 每一個葉子節點都是黑色的空節點(NIL節點)。
  • 每一個紅色節點的兩個子節點都是黑色。(從每一個葉子到根的全部路徑上不能有兩個連續的紅色節點)
  • 從任一節點到其每一個葉子的全部路徑都包含相同數目的黑色節點。

    從上面的條件能夠看出,a確定是不會違背的。插入的節點不在根節點處,因此b也不會違背。插入的節點時非空節點,c也不會違背。最有可能違背的就是d和e。而在咱們插入節點時,先將要插入的節點顏色設置爲紅色,這樣也就不會違背e。因此,插入後只須要調整不違背e就能夠。
    插入後調整須要分三種狀況來處理:數據結構

  1. 插入的是根節點:app

    處理方法是直接將根節點顏色設置爲黑色
  2. 插入節點的父節點爲黑色節點或父節點爲根節點

    不須要處理this

  3. 插入節點的父節點時紅色節點

    這種又分爲三種狀況
    下面假設插入節點爲x,父節點爲xp,祖父節點爲xpp,祖父節點的左兒子爲xppl,祖父節點的右兒子爲xpprspa

  • S1:當前節點的父節點xp是紅色,且當前節點的祖父節xpp點的另外一個子節點(xppl或者xppr)也是紅色

    處理邏輯:將父節點xp設爲紅色,祖父節點的兒子節點(xppl或者xppr)設爲黑色,將祖父節點xpp設爲紅色,將祖父節點xpp設爲當前節點,繼續處理。code

  • S2:當前節點的父節點xp是紅色,祖父節點的兒子節點(xppl或者xppr)是黑色,且當前節點x是其父節點xp的右孩子

    處理邏輯:父節點xp做爲當前節點x, 以當前節點x爲支點進行左旋。ip

  • S3:當前節點的父節點xp是紅色,祖父節點的兒子節點(xppl或者xppr)是黑色,且當前節點是其父節點xp的左孩子

    處理邏輯:將父節點xp設置爲黑色,祖父節點xpp設置爲紅色,以祖父節點xpp爲支點進行右旋rem

四、刪除節點後調整紅黑樹

未完,待續。。。get

三、構造一棵紅黑樹

  1. 經過插入節點,構造紅黑樹
    如今給定節點8 5 3 9 12 1 4 2,依次插入紅黑樹中,具體流程見下圖:

clipboard.png

  1. 在紅黑樹中刪除節點

未完,待續。。。源碼

2、HashMap中的紅黑樹相關源碼

static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        TreeNode<K,V> parent;  // red-black tree links
        TreeNode<K,V> left;
        TreeNode<K,V> right;
        //在節點刪除後,需解除連接
        TreeNode<K,V> prev; 
        boolean red;
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }

        /**
         * 返回根節點
         */
        final TreeNode<K,V> root() {
            for (TreeNode<K,V> r = this, p;;) {
                if ((p = r.parent) == null)
                    return r;
                r = p;
            }
        }

        /**
         * 確保根節點就是第一個節點
         */
        static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) {
            int n;
            if (root != null && tab != null && (n = tab.length) > 0) {
                int index = (n - 1) & root.hash;
                TreeNode<K,V> first = (TreeNode<K,V>)tab[index];
                //若是根節點不是第一個節點,進行調整
                if (root != first) {
                    Node<K,V> rn;
                    tab[index] = root;
                    TreeNode<K,V> rp = root.prev;
                    if ((rn = root.next) != null)
                        ((TreeNode<K,V>)rn).prev = rp;
                    if (rp != null)
                        rp.next = rn;
                    if (first != null)
                        first.prev = root;
                    root.next = first;
                    root.prev = null;
                }
                assert checkInvariants(root);
            }
        }

        /**
         * 根據hash值和key查詢節點
         */
        final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
            TreeNode<K,V> p = this;
            do {
                int ph, dir; K pk;
                TreeNode<K,V> pl = p.left, pr = p.right, q;
                if ((ph = p.hash) > h)
                    p = pl;
                else if (ph < h)
                    p = pr;
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                else if (pl == null)
                    p = pr;
                else if (pr == null)
                    p = pl;
                else if ((kc != null ||
                          (kc = comparableClassFor(k)) != null) &&
                         (dir = compareComparables(kc, k, pk)) != 0)
                    p = (dir < 0) ? pl : pr;
                else if ((q = pr.find(h, k, kc)) != null)
                    return q;
                else
                    p = pl;
            } while (p != null);
            return null;
        }

        /**
         * 根據hash值和key查詢節點
         */
        final TreeNode<K,V> getTreeNode(int h, Object k) {
            return ((parent != null) ? root() : this).find(h, k, null);
        }

        /**
         * 將鏈表轉換爲紅黑樹
         */
        final void treeify(Node<K,V>[] tab) {
            TreeNode<K,V> root = null;
               //從第一個節點開始
            for (TreeNode<K,V> x = this, next; x != null; x = next) {
                next = (TreeNode<K,V>)x.next;
                x.left = x.right = null;
                //若是root節點爲null,x爲根節點,此節點爲黑色,父節點爲null
                if (root == null) {
                    x.parent = null;
                    x.red = false;
                    root = x;
                }
                else {
                  //x的key值
                    K k = x.key;
                   //x的hash值
                    int h = x.hash;
                    Class<?> kc = null;
                    for (TreeNode<K,V> p = root;;) {
                        int dir, ph;
                        K pk = p.key;
                        //左邊
                        if ((ph = p.hash) > h)
                            dir = -1;
                        //右邊
                        else if (ph < h)
                            dir = 1;
                        //經過仲裁方法判斷
                        else if ((kc == null &&
                                  (kc = comparableClassFor(k)) == null) ||
                                 (dir = compareComparables(kc, k, pk)) == 0)
                            dir = tieBreakOrder(k, pk);

                        TreeNode<K,V> xp = p;
                        //dir <=0 左子樹搜索,而且判斷左兒子是否爲空,表示是否到葉子節點
                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
                            x.parent = xp;
                            if (dir <= 0)
                                xp.left = x;
                            else
                                xp.right = x;
                            //插入元素,判斷是否平衡,而且調整
                            root = balanceInsertion(root, x);
                            break;
                        }
                    }
                }
            }
          //確保根節點就是第一個節點
            moveRootToFront(tab, root);
        }

        /**
         * 紅黑樹轉換爲鏈表
         */
        final Node<K,V> untreeify(HashMap<K,V> map) {
            Node<K,V> hd = null, tl = null;
            for (Node<K,V> q = this; q != null; q = q.next) {
                Node<K,V> p = map.replacementNode(q, null);
                if (tl == null)
                    hd = p;
                else
                    tl.next = p;
                tl = p;
            }
            return hd;
        }

        /**
         * 插入一個節點
         */
        final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                                       int h, K k, V v) {
            Class<?> kc = null;
            boolean searched = false;
            TreeNode<K,V> root = (parent != null) ? root() : this;
            //從根據點開始,和當前搜索節點的hash比較
            for (TreeNode<K,V> p = root;;) {
                int dir, ph; K pk;
                if ((ph = p.hash) > h)
                    dir = -1;
                else if (ph < h)
                    dir = 1;
                 //hash和key都一致
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0) {
                    if (!searched) {
                        TreeNode<K,V> q, ch;
                        searched = true;
                        if (((ch = p.left) != null &&
                             (q = ch.find(h, k, kc)) != null) ||
                            ((ch = p.right) != null &&
                             (q = ch.find(h, k, kc)) != null))
                            return q;
                    }
                    dir = tieBreakOrder(k, pk);
                }

                TreeNode<K,V> xp = p;
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    Node<K,V> xpn = xp.next;
                    //新建節點
                    TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
                    if (dir <= 0)
                        xp.left = x;
                    else
                        xp.right = x;
                    xp.next = x;
                    x.parent = x.prev = xp;
                    if (xpn != null)
                        ((TreeNode<K,V>)xpn).prev = x;
                   //插入元素,判斷是否平衡,而且調整。確保根節點就是第一個節點
                    moveRootToFront(tab, balanceInsertion(root, x));
                    return null;
                }
            }
        }

        /**
         * Removes the given node, that must be present before this call.
         * This is messier than typical red-black deletion code because we
         * cannot swap the contents of an interior node with a leaf
         * successor that is pinned by "next" pointers that are accessible
         * independently during traversal. So instead we swap the tree
         * linkages. If the current tree appears to have too few nodes,
         * the bin is converted back to a plain bin. (The test triggers
         * somewhere between 2 and 6 nodes, depending on tree structure).
         */
        final void removeTreeNode(HashMap<K,V> map, Node<K,V>[] tab,
                                  boolean movable) {
            int n;
            if (tab == null || (n = tab.length) == 0)
                return;
            int index = (n - 1) & hash;
            TreeNode<K,V> first = (TreeNode<K,V>)tab[index], root = first, rl;
            TreeNode<K,V> succ = (TreeNode<K,V>)next, pred = prev;
            if (pred == null)
                tab[index] = first = succ;
            else
                pred.next = succ;
            if (succ != null)
                succ.prev = pred;
            if (first == null)
                return;
            if (root.parent != null)
                root = root.root();
            if (root == null || root.right == null ||
                (rl = root.left) == null || rl.left == null) {
                tab[index] = first.untreeify(map);  // too small
                return;
            }
            TreeNode<K,V> p = this, pl = left, pr = right, replacement;
            if (pl != null && pr != null) {
                TreeNode<K,V> s = pr, sl;
                while ((sl = s.left) != null) // find successor
                    s = sl;
                boolean c = s.red; s.red = p.red; p.red = c; // swap colors
                TreeNode<K,V> sr = s.right;
                TreeNode<K,V> pp = p.parent;
                if (s == pr) { // p was s's direct parent
                    p.parent = s;
                    s.right = p;
                }
                else {
                    TreeNode<K,V> sp = s.parent;
                    if ((p.parent = sp) != null) {
                        if (s == sp.left)
                            sp.left = p;
                        else
                            sp.right = p;
                    }
                    if ((s.right = pr) != null)
                        pr.parent = s;
                }
                p.left = null;
                if ((p.right = sr) != null)
                    sr.parent = p;
                if ((s.left = pl) != null)
                    pl.parent = s;
                if ((s.parent = pp) == null)
                    root = s;
                else if (p == pp.left)
                    pp.left = s;
                else
                    pp.right = s;
                if (sr != null)
                    replacement = sr;
                else
                    replacement = p;
            }
            else if (pl != null)
                replacement = pl;
            else if (pr != null)
                replacement = pr;
            else
                replacement = p;
            if (replacement != p) {
                TreeNode<K,V> pp = replacement.parent = p.parent;
                if (pp == null)
                    root = replacement;
                else if (p == pp.left)
                    pp.left = replacement;
                else
                    pp.right = replacement;
                p.left = p.right = p.parent = null;
            }

            TreeNode<K,V> r = p.red ? root : balanceDeletion(root, replacement);

            if (replacement == p) {  // detach
                TreeNode<K,V> pp = p.parent;
                p.parent = null;
                if (pp != null) {
                    if (p == pp.left)
                        pp.left = null;
                    else if (p == pp.right)
                        pp.right = null;
                }
            }
            if (movable)
                moveRootToFront(tab, r);
        }

        /* ------------------------------------------------------------ */
        // Red-black tree methods, all adapted from CLR
        //左旋
        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
                                              TreeNode<K,V> p) {
            TreeNode<K,V> r, pp, rl;
            //以p爲左旋支點,且p不爲空,右兒子不爲空
            if (p != null && (r = p.right) != null) {
                //將p的右兒子r的左兒子rl變爲p的右兒子
                if ((rl = p.right = r.left) != null)
                    rl.parent = p;
                //處理p、l和p父節點的關係
                if ((pp = r.parent = p.parent) == null)
                    (root = r).red = false;
                else if (pp.left == p)
                    pp.left = r;
                else
                    pp.right = r;
               //處理p和r的關係
                r.left = p;
                p.parent = r;
            }
            return root;
        }
        //右旋
        static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
                                               TreeNode<K,V> p) {
            TreeNode<K,V> l, pp, lr;
             //p:右旋支點,不爲空,p的左兒子l不爲空
            if (p != null && (l = p.left) != null) {
                 //將左兒子的右子樹變爲p的左子樹
                if ((lr = p.left = l.right) != null)
                    lr.parent = p;
                 //p的父節點變爲l的父節點
                if ((pp = l.parent = p.parent) == null)
                    (root = l).red = false;
             //若是p爲右兒子,則p的父節點的右兒子變爲l,不然左兒子變爲l
                else if (pp.right == p)
                    pp.right = l;
                else
                    pp.left = l;
                //p變爲l的右兒子
                l.right = p;
                p.parent = l;
            }
            return root;
        }

        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
                                                    TreeNode<K,V> x) {
           //插入節點初始化爲紅色
            x.red = true;
            //xp:父節點,xpp:祖父節點, xppl:祖父節點的左兒子,xppr:祖父節點的右兒子
             //循環遍歷
            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
                 //插入的節點爲根節點,節點顏色轉換爲黑色
                if ((xp = x.parent) == null) {
                    x.red = false;
                    return x;
                }
                 //當前節點的父爲黑色節點或者父節點爲根節點,直接返回
                else if (!xp.red || (xpp = xp.parent) == null)
                    return root;
                //祖父節點的左兒子是父節點
                if (xp == (xppl = xpp.left)) {
                    //S1:當前節點的父節點xp是紅色,且當前節點的祖父節xpp點的另外一個子節點(xppl或者xppr)也是紅色
                    if ((xppr = xpp.right) != null && xppr.red) {
                        xppr.red = false;
                        xp.red = false;
                        xpp.red = true;
                        x = xpp;
                    }
                    else {
                         //S2:當前節點的父節點xp是紅色,祖父節點的兒子節點(xppl或者xppr)是黑色,且當前節點x是其父節點xp的右孩子
                        if (x == xp.right) {
                            root = rotateLeft(root, x = xp);
                            xpp = (xp = x.parent) == null ? null : xp.parent;
                        }
                        //S3:當前節點的父節點xp是紅色,祖父節點的兒子節點(xppl或者xppr)是黑色,且當前節點是其父節點xp的左孩子
                        if (xp != null) {
                            xp.red = false;
                            if (xpp != null) {
                                xpp.red = true;
                                root = rotateRight(root, xpp);
                            }
                        }
                    }
                }
                else {
                    //S1:當前節點的父節點xp是紅色,且當前節點的祖父節xpp點的另外一個子節點(xppl或者xppr)也是紅色
                    if (xppl != null && xppl.red) {
                        xppl.red = false;
                        xp.red = false;
                        xpp.red = true;
                        x = xpp;
                    }
                    else {
                        //S2:當前節點的父節點xp是紅色,祖父節點的兒子節點(xppl或者xppr)是黑色,且當前節點x是其父節點xp的右孩子
                        if (x == xp.left) {
                            root = rotateRight(root, x = xp);
                            xpp = (xp = x.parent) == null ? null : xp.parent;
                        }
                        //S3:當前節點的父節點xp是紅色,祖父節點的兒子節點(xppl或者xppr)是黑色,且當前節點是其父節點xp的左孩子
                        if (xp != null) {
                            xp.red = false;
                            if (xpp != null) {
                                xpp.red = true;
                                root = rotateLeft(root, xpp);
                            }
                        }
                    }
                }
            }
        }

        static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
                                                   TreeNode<K,V> x) {
            for (TreeNode<K,V> xp, xpl, xpr;;)  {
                if (x == null || x == root)
                    return root;
                else if ((xp = x.parent) == null) {
                    x.red = false;
                    return x;
                }
                else if (x.red) {
                    x.red = false;
                    return root;
                }
                else if ((xpl = xp.left) == x) {
                    if ((xpr = xp.right) != null && xpr.red) {
                        xpr.red = false;
                        xp.red = true;
                        root = rotateLeft(root, xp);
                        xpr = (xp = x.parent) == null ? null : xp.right;
                    }
                    if (xpr == null)
                        x = xp;
                    else {
                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
                        if ((sr == null || !sr.red) &&
                            (sl == null || !sl.red)) {
                            xpr.red = true;
                            x = xp;
                        }
                        else {
                            if (sr == null || !sr.red) {
                                if (sl != null)
                                    sl.red = false;
                                xpr.red = true;
                                root = rotateRight(root, xpr);
                                xpr = (xp = x.parent) == null ?
                                    null : xp.right;
                            }
                            if (xpr != null) {
                                xpr.red = (xp == null) ? false : xp.red;
                                if ((sr = xpr.right) != null)
                                    sr.red = false;
                            }
                            if (xp != null) {
                                xp.red = false;
                                root = rotateLeft(root, xp);
                            }
                            x = root;
                        }
                    }
                }
                else { // symmetric
                    if (xpl != null && xpl.red) {
                        xpl.red = false;
                        xp.red = true;
                        root = rotateRight(root, xp);
                        xpl = (xp = x.parent) == null ? null : xp.left;
                    }
                    if (xpl == null)
                        x = xp;
                    else {
                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;
                        if ((sl == null || !sl.red) &&
                            (sr == null || !sr.red)) {
                            xpl.red = true;
                            x = xp;
                        }
                        else {
                            if (sl == null || !sl.red) {
                                if (sr != null)
                                    sr.red = false;
                                xpl.red = true;
                                root = rotateLeft(root, xpl);
                                xpl = (xp = x.parent) == null ?
                                    null : xp.left;
                            }
                            if (xpl != null) {
                                xpl.red = (xp == null) ? false : xp.red;
                                if ((sl = xpl.left) != null)
                                    sl.red = false;
                            }
                            if (xp != null) {
                                xp.red = false;
                                root = rotateRight(root, xp);
                            }
                            x = root;
                        }
                    }
                }
            }
        }
  }

3、總結

相關文章
相關標籤/搜索