红黑树

背景

二叉搜索树可以支持任何一种基本动态集合操作,二叉搜索树 介绍了高度为h的二叉搜索树的insert,search,getMin,getMax,delete等操作的时间复杂度都是o(h),但是如果数据量过大,还是会出现瓶颈,而红黑树是平衡搜索树的一种,在上面的这些动态操作的情况下,最坏的时间复杂度能缩短为o(lg n)。本文以HashMap的红黑二叉树为例,看看红黑二叉树的原理。

红黑树的定义:

红黑树有以下5个性质:

(1) 每个节点或者是黑色,或者是红色。
(2) 根节点是黑色。
(3) 每个叶子节点NIL是黑色。 [注意:这里叶子节点,是指为空的叶子节点!]
(4) 如果一个节点是红色的,则它的子节点必须是黑色的。
(5) 从一个节点到该节点的子孙节点的所有路径上包含相同数目的黑节点。

来自《算法导论》
来自《算法导论》

这里可以证明一个引理:一个有n歌内部节点的红黑树的高度最多为 2lg(n+1)。(具体的证明请看《算法导论》。)

用上面的引理可以证明,红黑树的时间复杂度是o(lg n)。相对于二叉搜索树,红黑树只是多了一个平衡的规则。

红黑树的类结构

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;    // needed to unlink next upon deletion
        boolean red;
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }

旋转

        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
                                              TreeNode<K,V> p) {
            TreeNode<K,V> r, pp, rl;
            if (p != null && (r = p.right) != null) {
                if ((rl = p.right = r.left) != null)
                    rl.parent = p;
                if ((pp = r.parent = p.parent) == null)
                    (root = r).red = false;
                else if (pp.left == p)
                    pp.left = r;
                else
                    pp.right = 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;
            if (p != null && (l = p.left) != null) {
                if ((lr = p.left = l.right) != null)
                    lr.parent = p;
                if ((pp = l.parent = p.parent) == null)
                    (root = l).red = false;
                else if (pp.right == p)
                    pp.right = l;
                else
                    pp.left = l;
                l.right = p;
                p.parent = l;
            }
            return root;
        }

插入

Hash的插入的思想是:

  • 先寻找这个节点存不存在在这棵树中。如果存在就返回(这里的算法和后面讲的find类似)然后hashMap的putValue会给这个entry做value替换。
  • 如果不存在在这棵树中,那么就做和二叉搜索树 一样寻找到一个null节点,做insert。
  • 最后也是相对于二叉搜索树 多出的一种操作:balanceInsertion(root, x)。这个操作叫做平衡插入,是用于维持这棵树的红黑性质的。
        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;  //拿到整棵树的根节点
            for (TreeNode<K,V> p = root;;) { //遍历整棵树
                int dir, ph; K pk;   //ph是p的hash值,pk是Key,dir是树该往左右走的方向。
                if ((ph = p.hash) > h)
                    dir = -1; // 要添加的元素应该放置在当前节点的左侧
                else if (ph < h)
                    dir = 1; // 要添加的元素应该放置在当前节点的右侧
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))   // 如果当前节点的键对象 和 指定key对象相同,表示该节点已经存在,然后会在putVal中的执行value的替换。
                    return p;
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0) {
                    /*
                     * searched 标识是否已经对比过当前节点的左右子节点了
                     * 如果还没有遍历过,那么就递归遍历对比,看是否能够得到那个键对象equals相等的的节点
                     * 如果得到了键的equals相等的的节点就返回
                     * 如果还是没有键的equals相等的节点,那说明应该创建一个新节点了
                     */
                    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;
                    }
                    // 走到这里就说明,遍历了所有子节点也没有找到和当前键equals相等的节点
                    dir = tieBreakOrder(k, pk);
                }

                TreeNode<K,V> xp = p;
                /*
                 * 如果dir小于等于0,那么看当前节点的左节点是否为空,如果为空,就可以把要添加的元素作为当前节点的左节点,如果不为空,还需要下一轮继续比较
                 * 如果dir大于等于0,那么看当前节点的右节点是否为空,如果为空,就可以把要添加的元素作为当前节点的右节点,如果不为空,还需要下一轮继续比较
                 * 如果以上两条当中有一个子节点不为空,这个if中还做了一件事,那就是把p已经指向了对应的不为空的子节点,开始下一轮的比较
                 */
                if ((p = (dir <= 0) ? p.left : p.right) == null) {  
                    // 如果恰好要添加的方向上的子节点为空,此时节点p已经指向了这个空的子节点
                    Node<K,V> xpn = xp.next; // 获取当前节点的next节点
                    TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn); // 创建一个新的树节点
                    if (dir <= 0)
                        xp.left = x;  // 左孩子指向到这个新的树节点
                    else
                        xp.right = x; // 右孩子指向到这个新的树节点
                    xp.next = x; // 链表中的next节点指向到这个新的树节点
                    x.parent = x.prev = xp; // 这个新的树节点的父节点、前节点均设置为 当前的树节点
                    if (xpn != null) // 如果原来的next节点不为空
                        ((TreeNode<K,V>)xpn).prev = x; // 那么原来的next节点的前节点指向到新的树节点
                    moveRootToFront(tab, balanceInsertion(root, x));// 重新平衡,以及新的根节点置顶
                    return null; // 返回空,意味着产生了一个新节点
                }
            }
        }

balanceInsertion

这个操作我理解是《算法导论中》的RB-INSERT-FIXUP。可以用下图来理解:

来自《算法导论》
  • a)插入后的结点z.由于z和它的父结点z.p都是红色的,所以违反了性质4。由于z的叔结点,是红色的,可以应用程序中的情况1.结点被重新着色,并且指针z沿树上升,所得的树如(b)所示。再一次之及其父结点又都为红色,但z的叔结点,是黑色的。因为z是z.p的右孩子,可以应用情况2。在执行1次左旋之后,所得结果树见(c).现在,是是其父结点的左孩子,可以应用情况3。重新着色并执行一次右旋后得(d)中的树,它是一棵合法的红黑树 。

上面的算法可以用下面的伪代码来理解:

        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
                                                    TreeNode<K,V> x) {
            x.red = true;// 新插入的节点标为红色
            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)) {
                    if ((xppr = xpp.right) != null && xppr.red) {
                        xppr.red = false;
                        xp.red = false;
                        xpp.red = true;
                        x = xpp;
                    }
                    else {
                        if (x == xp.right) {
                            root = rotateLeft(root, x = xp);
                            xpp = (xp = x.parent) == null ? null : xp.parent;
                        }
                        if (xp != null) {
                            xp.red = false;
                            if (xpp != null) {
                                xpp.red = true;
                                root = rotateRight(root, xpp);
                            }
                        }
                    }
                }
                else {
                    if (xppl != null && xppl.red) {
                        xppl.red = false;
                        xp.red = false;
                        xpp.red = true;
                        x = xpp;
                    }
                    else {
                        if (x == xp.left) {
                            root = rotateRight(root, x = xp);
                            xpp = (xp = x.parent) == null ? null : xp.parent;
                        }
                        if (xp != null) {
                            xp.red = false;
                            if (xpp != null) {
                                xpp.red = true;
                                root = rotateLeft(root, xpp);
                            }
                        }
                    }
                }
            }
        }

 

删除

删除的原理和insert差不多,不再概述。

        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
                || (movable
                    && (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);
        }

 


下面的东西只是和普通的二叉搜索树差不多。可以参考二叉搜索树 。

比如:

搜索

        /**
         * 这里是用hash值作为key。
         * Finds the node starting at root p with the given hash and key.
         * The kc argument caches comparableClassFor(key) upon first use
         * comparing keys.
         */
        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;
                //ph是根节点的hash值
                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.hash == h,但是左节点为空,则进入右结点
                    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;
        }

        /**
         * 返回根节点,从根节点开始寻找对象,确保寻找的东西在整棵树之内。
         * Calls find for root node.
         */
        final TreeNode<K,V> getTreeNode(int h, Object k) {
            return ((parent != null) ? root() : this).find(h, k, null);
        }

 


下面的东西只是一些辅助的方法。

获取根节点

        final TreeNode<K,V> root() {
            for (TreeNode<K,V> r = this, p;;) {
                if ((p = r.parent) == null)
                    return r;
                r = p;
            }
        }

 

        /**
         * Ensures that the given root is the first node of its bin.
         */
        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);
            }
        }

如果两者不具有compare的资格,或者compare之后仍然没有比较出大小。那么就要通过一个决胜局再比一次,这个决胜局就是tieBreakOrder方法。

        static int tieBreakOrder(Object a, Object b) {
            int d;
            if (a == null || b == null ||
                (d = a.getClass().getName().
                 compareTo(b.getClass().getName())) == 0)
                d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
                     -1 : 1);
            return d;
        }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值