TreeMap源码分析(red-black树)

来源:互联网 发布:python 显示 字符集 编辑:程序博客网 时间:2024/06/07 20:15

1.结构

Java在TreeMap类中实现了red-black树数据结构.TreeMap对象中的每个元素都包含两个部分:键和值.在TreeMap对象中没有两个元素具有相同的键.类结构如下:
这里写图片描述

可以看出,TreeMap类并不实现Collection接口.这是因为TreeMap类的方法大多是面向键-值关系的.

2.TreeMap

2.1 字段

    private final Comparator<? super K> comparator;    private transient Entry<K,V> root = null;    /**     * The number of entries in the tree     */    private transient int size = 0;    /**     * The number of structural modifications to the tree.     */    private transient int modCount = 0;    // Red-black mechanics    private static final boolean RED   = false;    private static final boolean BLACK = true;

comparator:比较器,用于对树结构的排序比较
root:根节点
size:树上节点的个数
modCount:和ArrayList中一样,用于迭代集合时的标志位
RED:red节点标识
BLACK:black节点标识

在这其中标识root的Entry类如下:

static final class Entry<K,V> implements Map.Entry<K,V> {        K key;        V value;        Entry<K,V> left = null;        Entry<K,V> right = null;        Entry<K,V> parent;        boolean color = BLACK;        /**         * Make a new cell with given key, value, and parent, and with         * {@code null} child links, and BLACK color.         */        Entry(K key, V value, Entry<K,V> parent) {            this.key = key;            this.value = value;            this.parent = parent;        }

可以看出,一个节点需要记录其左节点,右节点,父节点.默认的颜色是black.

2.2 构造器

public TreeMap() {        comparator = null;    } public TreeMap(Comparator<? super K> comparator) {        this.comparator = comparator;    }public TreeMap(Map<? extends K, ? extends V> m) {        comparator = null;        putAll(m);    }public TreeMap(SortedMap<K, ? extends V> m) {        comparator = m.comparator();        try {            buildFromSorted(m.size(), m.entrySet().iterator(), null, null);        } catch (java.io.IOException cannotHappen) {        } catch (ClassNotFoundException cannotHappen) {        }    }

前两个构造器引入了比较器.后两个方法与后续的put方法相似.

2.3 put方法

首先在put方法之前需要了解一下red-black树的基本描述,百度百科地址:http://baike.baidu.com/link?url=g9KOozogDuO7Zk5dlasjLutj-Dapul3iiR3g8Hvuf0W5fsuHe49srkMGqBZzaXqV0_vvzMVjronsOSYT_d8G7q

红黑树的性质:
1) 每个结点或是红的, 或是黑的.
2) 根结点是黑的.
3) 每个叶结点(NIL)是黑的.
4) 如果一个结点是红的, 则它的两个儿子是黑的.
5) 对每个结点, 从该结点到子孙结点的所有路径上包含相同数目的黑结点.

put方法如下:

public V put(K key, V value) {        Entry<K,V> t = root;        if (t == null) {            compare(key, key); // type (and possibly null) check            root = new Entry<>(key, value, null);            size = 1;            modCount++;            return null;        }        int cmp;        Entry<K,V> parent;        // split comparator and comparable paths        Comparator<? super K> cpr = comparator;        if (cpr != null) {            do {                parent = t;                cmp = cpr.compare(key, t.key);                if (cmp < 0)                    t = t.left;                else if (cmp > 0)                    t = t.right;                else                    return t.setValue(value);            } while (t != null);        }        else {            if (key == null)                throw new NullPointerException();            Comparable<? super K> k = (Comparable<? super K>) key;            do {                parent = t;                cmp = k.compareTo(t.key);                if (cmp < 0)                    t = t.left;                else if (cmp > 0)                    t = t.right;                else                    return t.setValue(value);            } while (t != null);        }        Entry<K,V> e = new Entry<>(key, value, parent);        if (cmp < 0)            parent.left = e;        else            parent.right = e;        fixAfterInsertion(e);        size++;        modCount++;        return null;    }

在这里我们分不同情况讨论.

2.3.1 t == null

这是插入第一个元素的情况,很简单,root = new Entry<>(key, value, null);直接创建一个即可.

2.3.2 t != null & cpr != null

Comparator cpr = comparator;如果在创建TreeMap的时候传入了比较器就使用这个比较器进行比较.do-while语句很显而易见表示,找到key值相应的位置.如果cmp=0,说明以前已经存过该key值就覆盖.cmp<0,向树的左边移动.cmp>0,向树的右边移动.

2.3.3 cpr == null

使用默认的比较器进行比较,比如int进行比较那肯定 2>1.

2.3.4 插入元素

插入元素方法也容易首先创建一个Entry e = new Entry<>(key, value, parent);然后将parent中的left或right指向该元素即可.

fixAfterInsertion方法是实现red-black的重点.

2.4 put方法中的fixAfterInsertion方法

该方法的主要作用是结构重排.方法如下:

 private void fixAfterInsertion(Entry<K,V> x) {        x.color = RED;        while (x != null && x != root && x.parent.color == RED) {            if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {                Entry<K,V> y = rightOf(parentOf(parentOf(x)));                if (colorOf(y) == RED) {                    setColor(parentOf(x), BLACK);                    setColor(y, BLACK);                    setColor(parentOf(parentOf(x)), RED);                    x = parentOf(parentOf(x));                } else {                    if (x == rightOf(parentOf(x))) {                        x = parentOf(x);                        rotateLeft(x);                    }                    setColor(parentOf(x), BLACK);                    setColor(parentOf(parentOf(x)), RED);                    rotateRight(parentOf(parentOf(x)));                }            } else {                Entry<K,V> y = leftOf(parentOf(parentOf(x)));                if (colorOf(y) == RED) {                    setColor(parentOf(x), BLACK);                    setColor(y, BLACK);                    setColor(parentOf(parentOf(x)), RED);                    x = parentOf(parentOf(x));                } else {                    if (x == leftOf(parentOf(x))) {                        x = parentOf(x);                        rotateRight(x);                    }                    setColor(parentOf(x), BLACK);                    setColor(parentOf(parentOf(x)), RED);                    rotateLeft(parentOf(parentOf(x)));                }            }        }        root.color = BLACK;    }

这里我们分几种情况:

2.4.1 colorOf(y) = RED

假如,元素30插入到一颗red-black树,结构如下:
这里写图片描述

此时操作有:
setColor(parentOf(x), BLACK);
setColor(y, BLACK);
setColor(parentOf(parentOf(x)), RED);
x = parentOf(parentOf(x));

操作完后结构如下:
这里写图片描述
此时不违反规则.

2.4.2 x == rightOf(parentOf(x)) & colorOf(y) = BLACK

该情况与上述情况相比,少了一个节点为60的元素.如下:
这里写图片描述
此时red结构被破坏,把20变为black也不行.此时需要进行旋转.操作如下:
x = parentOf(x);
rotateLeft(x);

首先将20和30进行左旋转.rotateLeft方法如下:

private void rotateLeft(Entry<K,V> p) {        if (p != null) {            Entry<K,V> r = p.right;            p.right = r.left;            if (r.left != null)                r.left.parent = p;            r.parent = p.parent;            if (p.parent == null)                root = r;            else if (p.parent.left == p)                p.parent.left = r;            else                p.parent.right = r;            r.left = p;            p.parent = r;        }    }

进行左旋后结构如下:
这里写图片描述

再经过右旋修正.
setColor(parentOf(x), BLACK);
setColor(parentOf(parentOf(x)), RED);
rotateRight(parentOf(parentOf(x)));

最后结果如下:
这里写图片描述

余下代码中的实现方式与该方法相似.

2.5 getEntry方法

 final Entry<K,V> getEntry(Object key) {        // Offload comparator-based version for sake of performance        if (comparator != null)            return getEntryUsingComparator(key);        if (key == null)            throw new NullPointerException();        Comparable<? super K> k = (Comparable<? super K>) key;        Entry<K,V> p = root;        while (p != null) {            int cmp = k.compareTo(p.key);            if (cmp < 0)                p = p.left;            else if (cmp > 0)                p = p.right;            else                return p;        }        return null;    }

getEntry方法通过比较器一步一步查找相应的key,这也好理解.这里的循环次数与树的高度成正比.故使用red-black算法进行结构重组,可以提高查询速度.

这里还有getFirstEntry和getLastEntry方法,getFirstEntry方法如下:

final Entry<K,V> getFirstEntry() {        Entry<K,V> p = root;        if (p != null)            while (p.left != null)                p = p.left;        return p;    }

该方法就是找到最小的那个也就是p.left.

2.6 remove方法

public V remove(Object key) {        Entry<K,V> p = getEntry(key);        if (p == null)            return null;        V oldValue = p.value;        deleteEntry(p);        return oldValue;    }

其中的deleteEntry方法和put方法类似,再删除节点后需要对数进行重新染色或者重排序.

0 0
原创粉丝点击