算法-红黑树原理

红黑树简介

红黑树可以用作Map,来完全O(logN)的查找。和HashMap相比,优点是能遍历保持有序。红黑树与普通二叉查找树相比,红黑树是完美平衡的,如果按顺序由小到大插入,不会出现二叉树那样退化为O(N)的链表。

2-3树

先看一下2-3树,因为红黑树的发明者(算法红宝书的作者)说,红黑树是一种实现2-3树的数据结构。红黑只是为了获得一种统一的表达形式,而不是直接使用两种节点类型。

这里写图片描述

  • 2子-节点:含有一个键和两个子节点。左边子树都小于该节点的键值;右边子树都大于该节点的键值。
  • 3子-节点:含有两个键和三个子节点。左边子树都小于该节点的键;右边子树都大于该节点的键;中间子树在两键范围之内。

插入操作

向2子-节点中插入新键

这里写图片描述

  • 可以发现,查找到相应的位置后,并没有作为该结点的子树,而是将2子-节点转变为一个3子-节点
向最简单的3子-节点中插入新键

这里写图片描述

  • 最简单的3子-节点中插入,会临时变成一个4子-节点,但是4子-节点是不稳定的,马上会分解,结果如图。
向一个父节点为2子-节点的3子-节点插入新键

这里写图片描述

  • 首先也是先找到一个要插入位置,并临时变成一个4子-节点,马上会分解,分解的中间键会浮到父节点上面去。
  • 注意这个键的插入位置,不能是M,R的旁边,只能是插到叶子节点上。
  • 所以也可以得出一个推论:非叶子节点的3子-节点都是因为子树分解的键上浮形成的,而不是直接插入。
向一个父节点为3子-节点的3子-节点插入新键

这里写图片描述
- 第一步第二步还是老样子,找到位置,然后插入形成4子-节点分解。
- 然后分解的中间键会上浮,使父节点变成一个临时的4子-节点。父节点再分解上浮。
- 可以想象得出,当插入很多很多键后,会出现一连串的分解上浮,就像多米诺骨牌。且这种向上递归会很难实现,需要每个子节点都保存父节点的引用。此外,这种节点类型的不停改变的情况,就算实现了也不怎么优雅。

根节点为3子-节点的3子-节点插入新键(上面的特殊情况)

这里写图片描述
- 和上面其实差不多,但是根节点比较特殊,也单独拿出来看看。

看两个连续的例子

这里写图片描述

插入操作的总结
  1. 插入位置一定是叶子节点,包括2/3子-节点。
  2. 4子-节点会分解,且上浮的键为中间键。
  3. *这些插入和分解操作不会破坏树的平衡性。

红黑二叉查找树

从2-3树到红黑树比把大象装进冰箱还要容易,只要这样:

这里写图片描述
这里写图片描述

  • 红链接都是左链接
  • 没有任何一个节点同时和两条红链接相连;因为和两个红链接相连的等价于上面的4子-节点,不稳定会分解,分解的结果就是两条红链接都变成黑色,但是父节点要变红,即“红红得黑父变红”。
  • 也不能连续出现两条红链接,这也是一种4子-节点。
  • 该树是“黑色平衡”,任意叶子节点到根节点的路径上,经过的黑色链接相同。
  • ps:图中的红链接其实表示->a的颜色为红色
节点数据结构
private static final boolean RED = true;
private static final boolean BLACK = false;
private class Node{
    Key key;
    Value val;
    Node left, right;
    int N;//表示这颗子树的节点总数
    boolean color;
}
辅助操作,核心!

这里写图片描述

  • 这张图的排版不好,首先将目光聚集到最后一张图上,即上面所说的“红红得黑父变红”。
  • 然后将目光看到第一张图,“父变红”后就不满足了红黑树的第一条性质(即红链接为左链接),此时就需要左旋。
  • 中间一张图的右旋,就是代表4子节点的分解。下面有解释。

插入操作

向2子-节点中插入新键

这里写图片描述

  • 比节点小的键,直接左边插入一个红节点。
  • 比节点大的键,直接右边插入一个红节点,然后左旋。
    这里写图片描述
向一个3子-节点插入新键

这里写图片描述

  • 第一种情况:新键最大,插入一个红节点在右边,然后进行“红红得黑父变红”的flipColor操作(父节点为根节点就不会变色)。
  • 第二种情况:新键最小,会插在原红节点的左子树。如图中,c节点会进行右旋,使得b“上浮”以满足第三条性质,然后进行一次flipColor。
  • 第三种情况:新键为两键之间,会插在原红节点的右子树。如图,先进行一次左旋,满足红黑树的第一条性质,这时的情况就和上面一样,再右旋,最后颜色翻转。
根节点为3子-节点的3子-节点插入新键(上面的特殊情况)
  • 根节点必须为黑色,这已经说过了,但是filpColor这个操作是固定的,根节点会先变成红色,然后需要额外的判断来保证根节点的黑色。
  • 特别需要提的是:这步由红->黑的操作,会使叶子到根节点的黑色路径加一。
向树底部的3子-节点插入新键

这里写图片描述

  1. 找到位置,插入到红节点的左边
  2. 有两个连续的连续的红节点,代表着一个4子-节点,需要右旋分解
  3. 分解后发现,不满足性质二,需要flipColor(有没有发现,右旋必定和翻转颜色一起出现!
  4. 然后发现R这个红节点出现在右边,需要左旋。
红色的传递规律

这里写图片描述

  • 这是一张状态转移图,如果上面的东西看懂了,这张图可以好好看看。
  • 这其实就是一个伪代码,将需要判断的东西和顺序都写明白了,可以按照这个直接撸代码。
红黑树插入的总结
  1. 左旋,右旋,flipColor的含义和代码要记住。
  2. 新插入的节点一定是红节点。
  3. 左旋是为了满足红黑树第一条性质,优先进行。
  4. 右旋之后必定跟随着flipColor,这2步共同完成4子-节点的分解。
万众期待的代码
private Node root;

private class Node {...};
private boolean isRed(Node h);//我就不直接写,不得不回去看文章吧!
private boolean isBlack(Node h);
private Node rotateLeft(Node h);
private Node rotateRight(Node h);
private void flipColor(Node h);

public void put(Key key, Value val){
    root = put(root, key, val);
    root.color = BLACK;
}

Node put(Node h, Key key, Value val){
    if (h == null){
        return new Node(key, val, 1, RED);    // <1>
    }
    int cmp = key.compareTo(h.key);           // <2>
    if (cmp < 0)
        h.left = put(h.left, key, val);       // <3>
    else if (cmp > 0)
        h.right = put(h.right, key, val);     // <4>
    else
        h.val = val;                          // <5>

    if (isRed(h.right) && isBlack(h.left))    // <6>
        h = rotateLeft(h);
    if (isRed(h.left) && isRed(h.left.left))  // <7>
        h = rotateRight(h);
    if (isRed(h.left) && isRed(h.right))      // <8>
        flipColor(h);
    h.N = size(h.left) + size(h.right) + 1;   // <9>
    return h;
}
  1. 递归的出口,找到叶子节点并适当插入,并且还有初始化根节点的作用
  2. 比较key的大小,应该是返回key.hashcode() - h.key.hashcode()
  3. key小,往左子树递归查找位置
  4. key大,往右子树递归查找位置
  5. key命中,命中键则更新值,其实这里的判断还不够
  6. 判断是否违背第一条性质,违背则左旋
  7. 判断是否违背第二条性质,违背则右旋
  8. 判断是否违背第三条性质,违背则翻转颜色

ps: 三条性质再次列在这里, 读三遍!!!

  • 红链接(红节点)在左边。
  • 不能出现连续的红链接(红节点的左右都不能是红节点)。
  • 一个节点的左右不能都是红链接(红节点)。
对照着图片再复习一般流程

删除操作

这是更加更加麻烦的操作,据说一般面试最多最多考到红黑树的插入,考删除会爆炸的吧,但是也得学呀!从算法角度说,插入的操作已经很精妙了,删除的操作就厉害了。因为插入时候,2-3树的4子节点会马上分解;而删除时候就是2-3-4树了,4子-节点会保留下来。

这里写图片描述

  • 一个很大的区别是:2-3树的插入后进行变换(左旋->右旋->flipColor); 而2-3-4树是插入时候变换,变换完成后插入节点就不动了,所以才得以保留4子-节点。
删除最小键
  • 如果节点是一个3子-节点有2个键,就可以很容易删除,不说了。
  • 2子-节点只有1个键,不能直接删除,需要一些变换:
    • 根是2子-节点,左右均是2子-节点,组成一个4子-节点再删除最小值
    • 否则需要保证根节点的左子节点不是2子-节点,不如需要往右子节点借一个

这里写图片描述

沿着左子节点删除最小值的过程中,保证以下情况的处理

  • 如果当前节点的左子节点不是2子-节点,完成
  • 如果当前节点的左子节点是2-子节点而兄弟节点不是2子-节点,就移动一个过来。
  • 如果当前节点的左右子节点都是2子-节点,合并为一个4子-节点。
删除最小键代码
private Node balance(Node j){
    if (isRed(h.right))
        h = rotateLeft(h);
    if (isRed(h.right) && isBlack(h.left))
        h = rotateLeft(h);
    if (isRed(h.left) && isRed(h.left.left))
        h = rotateRight(h);
    if (isRed(h.left) && isRed(h.right))
        flipColor(h);
    h.N = size(h.left) + size(h.right) + 1;
    return h;
}
private Node moveRedLeft(Node h){ 
    // Assuming that h is red and both h.left and h.left.left
    // are black, make h.left or one of its children red.
    flipColors(h);
    if (isRed(h.right.left)){
        h.right = rotateRight(h.right);
        h = rotateLeft(h);
    }
    return h;
}
public void deleteMin(){
    if (!isRed(root.left) && !isRed(root.right))
        root.color = RED;
    root = deleteMin(root);
    if (!isEmpty()) root.color = BLACK;
}
private Node deleteMin(Node h){
    if (h.left == null)
        return null;
    if (!isRed(h.left) && !isRed(h.left.left))
        h = moveRedLeft(h);
    h.left = deleteMin(h.left);
    return balance(h);
}
删除最大值
private Node moveRedRight(Node h){ 
// Assuming that h is red and both h.right and h.right.left
// are black, make h.right or one of its children red.
    flipColors(h)
    if (!isRed(h.left.left))
        h = rotateRight(h);
    return h;
}
public void deleteMax(){
    if (!isRed(root.left) && !isRed(root.right))
        root.color = RED;
    root = deleteMax(root);
    if (!isEmpty()) root.color = BLACK;
}
private Node deleteMax(Node h){
    if (isRed(h.left))
        h = rotateRight(h);
    if (h.right == null)
        return null;
    if (!isRed(h.right) && !isRed(h.right.left))
        h = moveRedRight(h);
    h.right = deleteMax(h.right);
    return balance(h);
}
删除操作
public void delete(Key key){
    if (!isRed(root.left) && !isRed(root.right))
        root.color = RED;
    root = delete(root, key);
    if (!isEmpty()) root.color = BLACK;
}
private Node delete(Node h, Key key){
    if (key.compareTo(h.key) < 0){
        if (!isRed(h.left) && !isRed(h.left.left))
            h = moveRedLeft(h);
        h.left = delete(h.left, key);
    }
    else{
        if (isRed(h.left))
            h = rotateRight(h);
        if (key.compareTo(h.key) == 0 && (h.right == null))
            return null;
        if (!isRed(h.right) && !isRed(h.right.left))
            h = moveRedRight(h);
        if (key.compareTo(h.key) == 0){
            h.val = get(h.right, min(h.right).key);
            h.key = min(h.right).key;
            h.right = deleteMin(h.right);
        }
        else h.right = delete(h.right, key);
    }
    return balance(h);
}

其他不错的文章

http://blog.csdn.net/coslay/article/details/47083897
http://www.cs.princeton.edu/~rs/talks/LLRB/RedBlack.pdf

全部代码

package data_structure;
import java.util.*;
import java.util.LinkedList;


public class RedBlackBST<Key extends Comparable<Key>, Value> {

    private static final boolean RED   = true;
    private static final boolean BLACK = false;

    private Node root;     // root of the BST

    // BST helper node data type
    private class Node {
        private Key key;           // key
        private Value val;         // associated data
        private Node left, right;  // links to left and right subtrees
        private boolean color;     // color of parent link
        private int size;          // subtree count

        public Node(Key key, Value val, boolean color, int size) {
            this.key = key;
            this.val = val;
            this.color = color;
            this.size = size;
        }
    }

    /**
     * Initializes an empty symbol table.
     */
    public RedBlackBST() {
    }

   /***************************************************************************
    *  Node helper methods.
    ***************************************************************************/
    // is node x red; false if x is null ?
    private boolean isRed(Node x) {
        if (x == null) return false;
        return x.color == RED;
    }

    // number of node in subtree rooted at x; 0 if x is null
    private int size(Node x) {
        if (x == null) return 0;
        return x.size;
    } 


    /**
     * Returns the number of key-value pairs in this symbol table.
     * @return the number of key-value pairs in this symbol table
     */
    public int size() {
        return size(root);
    }

   /**
     * Is this symbol table empty?
     * @return {@code true} if this symbol table is empty and {@code false} otherwise
     */
    public boolean isEmpty() {
        return root == null;
    }


   /***************************************************************************
    *  Standard BST search.
    ***************************************************************************/

    /**
     * Returns the value associated with the given key.
     * @param key the key
     * @return the value associated with the given key if the key is in the symbol table
     *     and {@code null} if the key is not in the symbol table
     * @throws IllegalArgumentException if {@code key} is {@code null}
     */
    public Value get(Key key) {
        if (key == null) throw new IllegalArgumentException("argument to get() is null");
        return get(root, key);
    }

    // value associated with the given key in subtree rooted at x; null if no such key
    private Value get(Node x, Key key) {
        while (x != null) {
            int cmp = key.compareTo(x.key);
            if      (cmp < 0) x = x.left;
            else if (cmp > 0) x = x.right;
            else              return x.val;
        }
        return null;
    }

    /**
     * Does this symbol table contain the given key?
     * @param key the key
     * @return {@code true} if this symbol table contains {@code key} and
     *     {@code false} otherwise
     * @throws IllegalArgumentException if {@code key} is {@code null}
     */
    public boolean contains(Key key) {
        return get(key) != null;
    }

   /***************************************************************************
    *  Red-black tree insertion.
    ***************************************************************************/

    /**
     * Inserts the specified key-value pair into the symbol table, overwriting the old 
     * value with the new value if the symbol table already contains the specified key.
     * Deletes the specified key (and its associated value) from this symbol table
     * if the specified value is {@code null}.
     *
     * @param key the key
     * @param val the value
     * @throws IllegalArgumentException if {@code key} is {@code null}
     */
    public void put(Key key, Value val) {
        if (key == null) throw new IllegalArgumentException("first argument to put() is null");
        if (val == null) {
            delete(key);
            return;
        }

        root = put(root, key, val);
        root.color = BLACK;
        // assert check();
    }

    // insert the key-value pair in the subtree rooted at h
    private Node put(Node h, Key key, Value val) { 
        if (h == null) return new Node(key, val, RED, 1);

        int cmp = key.compareTo(h.key);
        if      (cmp < 0) h.left  = put(h.left,  key, val); 
        else if (cmp > 0) h.right = put(h.right, key, val); 
        else              h.val   = val;

        // fix-up any right-leaning links
        if (isRed(h.right) && !isRed(h.left))      h = rotateLeft(h);
        if (isRed(h.left)  &&  isRed(h.left.left)) h = rotateRight(h);
        if (isRed(h.left)  &&  isRed(h.right))     flipColors(h);
        h.size = size(h.left) + size(h.right) + 1;

        return h;
    }

   /***************************************************************************
    *  Red-black tree deletion.
    ***************************************************************************/

    /**
     * Removes the smallest key and associated value from the symbol table.
     * @throws NoSuchElementException if the symbol table is empty
     */
    public void deleteMin() {
        if (isEmpty()) throw new NoSuchElementException("BST underflow");

        // if both children of root are black, set root to red
        if (!isRed(root.left) && !isRed(root.right))
            root.color = RED;

        root = deleteMin(root);
        if (!isEmpty()) root.color = BLACK;
        // assert check();
    }

    // delete the key-value pair with the minimum key rooted at h
    private Node deleteMin(Node h) { 
        if (h.left == null)
            return null;

        if (!isRed(h.left) && !isRed(h.left.left))
            h = moveRedLeft(h);

        h.left = deleteMin(h.left);
        return balance(h);
    }


    /**
     * Removes the largest key and associated value from the symbol table.
     * @throws NoSuchElementException if the symbol table is empty
     */
    public void deleteMax() {
        if (isEmpty()) throw new NoSuchElementException("BST underflow");

        // if both children of root are black, set root to red
        if (!isRed(root.left) && !isRed(root.right))
            root.color = RED;

        root = deleteMax(root);
        if (!isEmpty()) root.color = BLACK;
        // assert check();
    }

    // delete the key-value pair with the maximum key rooted at h
    private Node deleteMax(Node h) { 
        if (isRed(h.left))
            h = rotateRight(h);

        if (h.right == null)
            return null;

        if (!isRed(h.right) && !isRed(h.right.left))
            h = moveRedRight(h);

        h.right = deleteMax(h.right);

        return balance(h);
    }

    /**
     * Removes the specified key and its associated value from this symbol table     
     * (if the key is in this symbol table).    
     *
     * @param  key the key
     * @throws IllegalArgumentException if {@code key} is {@code null}
     */
    public void delete(Key key) { 
        if (key == null) throw new IllegalArgumentException("argument to delete() is null");
        if (!contains(key)) return;

        // if both children of root are black, set root to red
        if (!isRed(root.left) && !isRed(root.right))
            root.color = RED;

        root = delete(root, key);
        if (!isEmpty()) root.color = BLACK;
        // assert check();
    }

    // delete the key-value pair with the given key rooted at h
    private Node delete(Node h, Key key) { 
        // assert get(h, key) != null;

        if (key.compareTo(h.key) < 0)  {
            if (!isRed(h.left) && !isRed(h.left.left))
                h = moveRedLeft(h);
            h.left = delete(h.left, key);
        }
        else {
            if (isRed(h.left))
                h = rotateRight(h);
            if (key.compareTo(h.key) == 0 && (h.right == null))
                return null;
            if (!isRed(h.right) && !isRed(h.right.left))
                h = moveRedRight(h);
            if (key.compareTo(h.key) == 0) {
                Node x = min(h.right);
                h.key = x.key;
                h.val = x.val;
                // h.val = get(h.right, min(h.right).key);
                // h.key = min(h.right).key;
                h.right = deleteMin(h.right);
            }
            else h.right = delete(h.right, key);
        }
        return balance(h);
    }

   /***************************************************************************
    *  Red-black tree helper functions.
    ***************************************************************************/

    // make a left-leaning link lean to the right
    private Node rotateRight(Node h) {
        // assert (h != null) && isRed(h.left);
        Node x = h.left;
        h.left = x.right;
        x.right = h;
        x.color = x.right.color;
        x.right.color = RED;
        x.size = h.size;
        h.size = size(h.left) + size(h.right) + 1;
        return x;
    }

    // make a right-leaning link lean to the left
    private Node rotateLeft(Node h) {
        // assert (h != null) && isRed(h.right);
        Node x = h.right;
        h.right = x.left;
        x.left = h;
        x.color = x.left.color;
        x.left.color = RED;
        x.size = h.size;
        h.size = size(h.left) + size(h.right) + 1;
        return x;
    }

    // flip the colors of a node and its two children
    private void flipColors(Node h) {
        // h must have opposite color of its two children
        // assert (h != null) && (h.left != null) && (h.right != null);
        // assert (!isRed(h) &&  isRed(h.left) &&  isRed(h.right))
        //    || (isRed(h)  && !isRed(h.left) && !isRed(h.right));
        h.color = !h.color;
        h.left.color = !h.left.color;
        h.right.color = !h.right.color;
    }

    // Assuming that h is red and both h.left and h.left.left
    // are black, make h.left or one of its children red.
    private Node moveRedLeft(Node h) {
        // assert (h != null);
        // assert isRed(h) && !isRed(h.left) && !isRed(h.left.left);

        flipColors(h);
        if (isRed(h.right.left)) { 
            h.right = rotateRight(h.right);
            h = rotateLeft(h);
            flipColors(h);
        }
        return h;
    }

    // Assuming that h is red and both h.right and h.right.left
    // are black, make h.right or one of its children red.
    private Node moveRedRight(Node h) {
        // assert (h != null);
        // assert isRed(h) && !isRed(h.right) && !isRed(h.right.left);
        flipColors(h);
        if (isRed(h.left.left)) { 
            h = rotateRight(h);
            flipColors(h);
        }
        return h;
    }

    // restore red-black tree invariant
    private Node balance(Node h) {
        // assert (h != null);

        if (isRed(h.right))                      h = rotateLeft(h);
        if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h);
        if (isRed(h.left) && isRed(h.right))     flipColors(h);

        h.size = size(h.left) + size(h.right) + 1;
        return h;
    }


   /***************************************************************************
    *  Utility functions.
    ***************************************************************************/

    /**
     * Returns the height of the BST (for debugging).
     * @return the height of the BST (a 1-node tree has height 0)
     */
    public int height() {
        return height(root);
    }
    private int height(Node x) {
        if (x == null) return -1;
        return 1 + Math.max(height(x.left), height(x.right));
    }

   /***************************************************************************
    *  Ordered symbol table methods.
    ***************************************************************************/

    /**
     * Returns the smallest key in the symbol table.
     * @return the smallest key in the symbol table
     * @throws NoSuchElementException if the symbol table is empty
     */
    public Key min() {
        if (isEmpty()) throw new NoSuchElementException("calls min() with empty symbol table");
        return min(root).key;
    } 

    // the smallest key in subtree rooted at x; null if no such key
    private Node min(Node x) { 
        // assert x != null;
        if (x.left == null) return x; 
        else                return min(x.left); 
    } 

    /**
     * Returns the largest key in the symbol table.
     * @return the largest key in the symbol table
     * @throws NoSuchElementException if the symbol table is empty
     */
    public Key max() {
        if (isEmpty()) throw new NoSuchElementException("calls max() with empty symbol table");
        return max(root).key;
    } 

    // the largest key in the subtree rooted at x; null if no such key
    private Node max(Node x) { 
        // assert x != null;
        if (x.right == null) return x; 
        else                 return max(x.right); 
    } 


    /**
     * Returns the largest key in the symbol table less than or equal to {@code key}.
     * @param key the key
     * @return the largest key in the symbol table less than or equal to {@code key}
     * @throws NoSuchElementException if there is no such key
     * @throws IllegalArgumentException if {@code key} is {@code null}
     */
    public Key floor(Key key) {
        if (key == null) throw new IllegalArgumentException("argument to floor() is null");
        if (isEmpty()) throw new NoSuchElementException("calls floor() with empty symbol table");
        Node x = floor(root, key);
        if (x == null) return null;
        else           return x.key;
    }    

    // the largest key in the subtree rooted at x less than or equal to the given key
    private Node floor(Node x, Key key) {
        if (x == null) return null;
        int cmp = key.compareTo(x.key);
        if (cmp == 0) return x;
        if (cmp < 0)  return floor(x.left, key);
        Node t = floor(x.right, key);
        if (t != null) return t; 
        else           return x;
    }

    /**
     * Returns the smallest key in the symbol table greater than or equal to {@code key}.
     * @param key the key
     * @return the smallest key in the symbol table greater than or equal to {@code key}
     * @throws NoSuchElementException if there is no such key
     * @throws IllegalArgumentException if {@code key} is {@code null}
     */
    public Key ceiling(Key key) {
        if (key == null) throw new IllegalArgumentException("argument to ceiling() is null");
        if (isEmpty()) throw new NoSuchElementException("calls ceiling() with empty symbol table");
        Node x = ceiling(root, key);
        if (x == null) return null;
        else           return x.key;  
    }

    // the smallest key in the subtree rooted at x greater than or equal to the given key
    private Node ceiling(Node x, Key key) {  
        if (x == null) return null;
        int cmp = key.compareTo(x.key);
        if (cmp == 0) return x;
        if (cmp > 0)  return ceiling(x.right, key);
        Node t = ceiling(x.left, key);
        if (t != null) return t; 
        else           return x;
    }

    /**
     * Return the kth smallest key in the symbol table.
     * @param k the order statistic
     * @return the {@code k}th smallest key in the symbol table
     * @throws IllegalArgumentException unless {@code k} is between 0 and
     *     <em>n</em>–1
     */
    public Key select(int k) {
        if (k < 0 || k >= size()) {
            throw new IllegalArgumentException("argument to select() is invalid: " + k);
        }
        Node x = select(root, k);
        return x.key;
    }

    // the key of rank k in the subtree rooted at x
    private Node select(Node x, int k) {
        // assert x != null;
        // assert k >= 0 && k < size(x);
        int t = size(x.left); 
        if      (t > k) return select(x.left,  k); 
        else if (t < k) return select(x.right, k-t-1); 
        else            return x; 
    } 

    /**
     * Return the number of keys in the symbol table strictly less than {@code key}.
     * @param key the key
     * @return the number of keys in the symbol table strictly less than {@code key}
     * @throws IllegalArgumentException if {@code key} is {@code null}
     */
    public int rank(Key key) {
        if (key == null) throw new IllegalArgumentException("argument to rank() is null");
        return rank(key, root);
    } 

    // number of keys less than key in the subtree rooted at x
    private int rank(Key key, Node x) {
        if (x == null) return 0; 
        int cmp = key.compareTo(x.key); 
        if      (cmp < 0) return rank(key, x.left); 
        else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right); 
        else              return size(x.left); 
    } 

   /***************************************************************************
    *  Range count and range search.
    ***************************************************************************/

    /**
     * Returns all keys in the symbol table as an {@code Iterable}.
     * To iterate over all of the keys in the symbol table named {@code st},
     * use the foreach notation: {@code for (Key key : st.keys())}.
     * @return all keys in the symbol table as an {@code Iterable}
     */
    public Iterable<Key> keys() {
        if (isEmpty()) return new LinkedList<>();
        return keys(min(), max());
    }

    /**
     * Returns all keys in the symbol table in the given range,
     * as an {@code Iterable}.
     *
     * @param  lo minimum endpoint
     * @param  hi maximum endpoint
     * @return all keys in the sybol table between {@code lo} 
     *    (inclusive) and {@code hi} (inclusive) as an {@code Iterable}
     * @throws IllegalArgumentException if either {@code lo} or {@code hi}
     *    is {@code null}
     */
    public Iterable<Key> keys(Key lo, Key hi) {
        if (lo == null) throw new IllegalArgumentException("first argument to keys() is null");
        if (hi == null) throw new IllegalArgumentException("second argument to keys() is null");

        Queue<Key> queue = new LinkedList<>();
        // if (isEmpty() || lo.compareTo(hi) > 0) return queue;
        keys(root, queue, lo, hi);
        return queue;
    } 

    // add the keys between lo and hi in the subtree rooted at x
    // to the queue
    private void keys(Node x, Queue<Key> queue, Key lo, Key hi) { 
        if (x == null) return; 
        int cmplo = lo.compareTo(x.key); 
        int cmphi = hi.compareTo(x.key); 
        if (cmplo < 0) keys(x.left, queue, lo, hi); 
        if (cmplo <= 0 && cmphi >= 0) queue.add(x.key);
        if (cmphi > 0) keys(x.right, queue, lo, hi); 
    } 

    /**
     * Returns the number of keys in the symbol table in the given range.
     *
     * @param  lo minimum endpoint
     * @param  hi maximum endpoint
     * @return the number of keys in the sybol table between {@code lo} 
     *    (inclusive) and {@code hi} (inclusive)
     * @throws IllegalArgumentException if either {@code lo} or {@code hi}
     *    is {@code null}
     */
    public int size(Key lo, Key hi) {
        if (lo == null) throw new IllegalArgumentException("first argument to size() is null");
        if (hi == null) throw new IllegalArgumentException("second argument to size() is null");

        if (lo.compareTo(hi) > 0) return 0;
        if (contains(hi)) return rank(hi) - rank(lo) + 1;
        else              return rank(hi) - rank(lo);
    }


   /***************************************************************************
    *  Check integrity of red-black tree data structure.
    ***************************************************************************/
    private boolean check() {
        if (!isBST())            System.out.println("Not in symmetric order");
        if (!isSizeConsistent()) System.out.println("Subtree counts not consistent");
        if (!isRankConsistent()) System.out.println("Ranks not consistent");
        if (!is23())             System.out.println("Not a 2-3 tree");
        if (!isBalanced())       System.out.println("Not balanced");
        return isBST() && isSizeConsistent() && isRankConsistent() && is23() && isBalanced();
    }

    // does this binary tree satisfy symmetric order?
    // Note: this test also ensures that data structure is a binary tree since order is strict
    private boolean isBST() {
        return isBST(root, null, null);
    }

    // is the tree rooted at x a BST with all keys strictly between min and max
    // (if min or max is null, treat as empty constraint)
    // Credit: Bob Dondero's elegant solution
    private boolean isBST(Node x, Key min, Key max) {
        if (x == null) return true;
        if (min != null && x.key.compareTo(min) <= 0) return false;
        if (max != null && x.key.compareTo(max) >= 0) return false;
        return isBST(x.left, min, x.key) && isBST(x.right, x.key, max);
    } 

    // are the size fields correct?
    private boolean isSizeConsistent() { return isSizeConsistent(root); }
    private boolean isSizeConsistent(Node x) {
        if (x == null) return true;
        if (x.size != size(x.left) + size(x.right) + 1) return false;
        return isSizeConsistent(x.left) && isSizeConsistent(x.right);
    } 

    // check that ranks are consistent
    private boolean isRankConsistent() {
        for (int i = 0; i < size(); i++)
            if (i != rank(select(i))) return false;
        for (Key key : keys())
            if (key.compareTo(select(rank(key))) != 0) return false;
        return true;
    }

    // Does the tree have no red right links, and at most one (left)
    // red links in a row on any path?
    private boolean is23() { return is23(root); }
    private boolean is23(Node x) {
        if (x == null) return true;
        if (isRed(x.right)) return false;
        if (x != root && isRed(x) && isRed(x.left))
            return false;
        return is23(x.left) && is23(x.right);
    } 

    // do all paths from root to leaf have same number of black edges?
    private boolean isBalanced() { 
        int black = 0;     // number of black links on path from root to min
        Node x = root;
        while (x != null) {
            if (!isRed(x)) black++;
            x = x.left;
        }
        return isBalanced(root, black);
    }

    // does every path from the root to a leaf have the given number of black links?
    private boolean isBalanced(Node x, int black) {
        if (x == null) return black == 0;
        if (!isRed(x)) black--;
        return isBalanced(x.left, black) && isBalanced(x.right, black);
    } 


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值