TreeMap 底层使用的是红黑树的结构,查询或者修改的时间复杂度为 O(logN),前面我们在 HashMap 篇以及 ConcurrentHashMap 篇中跳过了红黑树的处理部分,本篇将对红黑树进行详细的介绍。
1. 红黑树
红黑树是在二叉树的基础上进行了一些约束来使二叉树趋于平衡,它是二叉查找树的一种实现。这些约束有:
- 每个节点必须是黑色或红色;
- 根节点必须是黑色;
- 叶子节点必须是黑色的空心节点;
- 红色节点的两个子节点必须是黑色;
- 从根节点到任何一个叶子节点的路径所经过的黑色节点树必须相同。
2. 属性及构造
/**
* The comparator used to maintain order in this tree map, or
* null if it uses the natural ordering of its keys.
*
* @serial
*/
// 比较器,作为查找树,需要有排序规则,
// 可以构造时传入,不传则使用字典排序规则比较
private final Comparator<? super K> comparator;
// 红黑树的根节点
private transient Entry<K,V> root;
/**
* 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;
/**
* Constructs a new, empty tree map, using the natural ordering of its
* keys. All keys inserted into the map must implement the {@link
* Comparable} interface. Furthermore, all such keys must be
* <em>mutually comparable</em>: {@code k1.compareTo(k2)} must not throw
* a {@code ClassCastException} for any keys {@code k1} and
* {@code k2} in the map. If the user attempts to put a key into the
* map that violates this constraint (for example, the user attempts to
* put a string key into a map whose keys are integers), the
* {@code put(Object key, Object value)} call will throw a
* {@code ClassCastException}.
*/
public TreeMap() {
comparator = null;
}
/**
* Constructs a new, empty tree map, ordered according to the given
* comparator. All keys inserted into the map must be <em>mutually
* comparable</em> by the given comparator: {@code comparator.compare(k1,
* k2)} must not throw a {@code ClassCastException} for any keys
* {@code k1} and {@code k2} in the map. If the user attempts to put
* a key into the map that violates this constraint, the {@code put(Object
* key, Object value)} call will throw a
* {@code ClassCastException}.
*
* @param comparator the comparator that will be used to order this map.
* If {@code null}, the {@linkplain Comparable natural
* ordering} of the keys will be used.
*/
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
/**
* Constructs a new tree map containing the same mappings as the given
* map, ordered according to the <em>natural ordering</em> of its keys.
* All keys inserted into the new map must implement the {@link
* Comparable} interface. Furthermore, all such keys must be
* <em>mutually comparable</em>: {@code k1.compareTo(k2)} must not throw
* a {@code ClassCastException} for any keys {@code k1} and
* {@code k2} in the map. This method runs in n*log(n) time.
*
* @param m the map whose mappings are to be placed in this map
* @throws ClassCastException if the keys in m are not {@link Comparable},
* or are not mutually comparable
* @throws NullPointerException if the specified map is null
*/
public TreeMap(Map<? extends K, ? extends V> m) {
comparator = null;
putAll(m);
}
3. 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
// 如果要插入的 key 与已有的相等,只覆盖值即可
return t.setValue(value);
} while (t != null);
}
// 比较器为空,按照天然的比较准则比较查找
else {
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
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
// 如果要插入的 key 与已有的相等,只覆盖值即可
// 值的覆盖不改变树的结构,因此不计入修改次数
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;
}
fixAfterInsertion()
private void fixAfterInsertion(Entry<K,V> x) {
// 插入的节点,颜色被设置成红色。
// 因为这样使插入后的树违反的规则最少,降低修复的代价。
x.color = RED;
// 循环的条件:x 节点不为空,且 x 不为根节点,且父节点为红色
while (x != null && x != root && x.parent.color == RED) {
// 如果父节点是祖父节点的左子节点
if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
// y 为 x 的叔叔节点(x 父节点的同级节点)
Entry<K,V> y = rightOf(parentOf(parentOf(x)));
// 综合以上条件,此时:
// x 的父节点为红色,叔叔节点也为红色。
// 这种情况下的处理方式为:
// 1.将父节点着为黑色;
// 2.将叔叔节点着为黑色;
// 3.将祖父节点着为红色;
// 4.将祖父节点设置为 x 继续下轮循环处理
if (colorOf(y) == RED) {
setColor(parentOf(x), BLACK);
setColor(y, BLACK);
setColor(parentOf(parentOf(x)), RED);
x = parentOf(parentOf(x));
}
// 综合以上条件,此时:
// x 的父节点为红色,叔叔节点为黑色。
// 这种情况下的处理方式为:
else {
// 如果 x 为父节点的右子节点:
// 1. 将父节点设为当前节点 x;
// 2. 将当前节点左旋。
// 3. 将父节点着为黑色。
// 4. 将祖父节点着为黑色。
// 5. 将祖父节点右旋。
if (x == rightOf(parentOf(x))) {
x = parentOf(x);
rotateLeft(x);
}
// 如果 x 为父节点的左子节点,只需要执行上面的 3、4、5
setColor(parentOf(x), BLACK);
setColor(parentOf(parentOf(x)), RED);
rotateRight(parentOf(parentOf(x)));
}
}
// 如果父节点是祖父节点的右子节点,处理方式与上面是对称的。
else {
// y 为 x 的叔叔节点(x 父节点的同级节点)
Entry<K,V> y = leftOf(parentOf(parentOf(x)));
// 综合以上条件,此时:
// x 的父节点为红色,叔叔节点也为红色。
// 这种情况下的处理方式为:
// 1.将父节点着为黑色;
// 2.将叔叔节点着为黑色;
// 3.将祖父节点着为红色;
// 4.将祖父节点设置为 x 继续下轮循环处理
if (colorOf(y) == RED) {
setColor(parentOf(x), BLACK);
setColor(y, BLACK);
setColor(parentOf(parentOf(x)), RED);
x = parentOf(parentOf(x));
}
// 综合以上条件,此时:
// x 的父节点为红色,叔叔节点为黑色。
// 这种情况下的处理方式为:
else {
// 如果 x 为父节点的左子节点:
// 1. 将父节点设为当前节点 x;
// 2. 将当前节点右旋。
// 3. 将父节点着为黑色。
// 4. 将祖父节点着为黑色。
// 5. 将祖父节点左旋。
if (x == leftOf(parentOf(x))) {
x = parentOf(x);
rotateRight(x);
}
// 如果 x 为父节点的右子节点,只需要执行上面的 3、4、5
setColor(parentOf(x), BLACK);
setColor(parentOf(parentOf(x)), RED);
rotateLeft(parentOf(parentOf(x)));
}
}
}
// 最后,将根节点着成黑色
root.color = BLACK;
}
4. 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;
}
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();
@SuppressWarnings("unchecked")
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;
}
deleteEntry()
private void deleteEntry(Entry<K,V> p) {
modCount++;
size--;
// If strictly internal, copy successor's element to p and then make p
// point to successor.
// 如果左右子树均不为空,用右子树替换掉要移除的节点。
if (p.left != null && p.right != null) {
// 查找 p 的后继节点--大于 p 的最小的节点。
// 二叉查找树中,p 的后继节点为 p 的右子树中的最小的节点。
Entry<K,V> s = successor(p);
p.key = s.key;
p.value = s.value;
p = s;
} // p has 2 children
// Start fixup at replacement node, if it exists.
// 修复替补节点
Entry<K,V> replacement = (p.left != null ? p.left : p.right);
if (replacement != null) {
// Link replacement to parent
replacement.parent = p.parent;
if (p.parent == null)
root = replacement;
else if (p == p.parent.left)
p.parent.left = replacement;
else
p.parent.right = replacement;
// Null out links so they are OK to use by fixAfterDeletion.
p.left = p.right = p.parent = null;
// Fix replacement
if (p.color == BLACK)
fixAfterDeletion(replacement);
} else if (p.parent == null) { // return if we are the only node.
root = null;
} else { // No children. Use self as phantom replacement and unlink.
if (p.color == BLACK)
fixAfterDeletion(p);
if (p.parent != null) {
if (p == p.parent.left)
p.parent.left = null;
else if (p == p.parent.right)
p.parent.right = null;
p.parent = null;
}
}
}
successor()
static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) {
if (t == null)
return null;
// 如果存在右子树,右子树中的值最小的节点即为后继节点
else if (t.right != null) {
Entry<K,V> p = t.right;
while (p.left != null)
p = p.left;
return p;
}
// 如果不存在右子树,向上找到右斜树的最小根节点即为后继节点
else {
Entry<K,V> p = t.parent;
Entry<K,V> ch = t;
while (p != null && ch == p.right) {
ch = p;
p = p.parent;
}
return p;
}
}
fixAfterDeletion()
// 移除节点后的修复和插入的修复相似
private void fixAfterDeletion(Entry<K,V> x) {
while (x != root && colorOf(x) == BLACK) {
if (x == leftOf(parentOf(x))) {
Entry<K,V> sib = rightOf(parentOf(x));
if (colorOf(sib) == RED) {
setColor(sib, BLACK);
setColor(parentOf(x), RED);
rotateLeft(parentOf(x));
sib = rightOf(parentOf(x));
}
if (colorOf(leftOf(sib)) == BLACK &&
colorOf(rightOf(sib)) == BLACK) {
setColor(sib, RED);
x = parentOf(x);
} else {
if (colorOf(rightOf(sib)) == BLACK) {
setColor(leftOf(sib), BLACK);
setColor(sib, RED);
rotateRight(sib);
sib = rightOf(parentOf(x));
}
setColor(sib, colorOf(parentOf(x)));
setColor(parentOf(x), BLACK);
setColor(rightOf(sib), BLACK);
rotateLeft(parentOf(x));
x = root;
}
} else { // symmetric
Entry<K,V> sib = leftOf(parentOf(x));
if (colorOf(sib) == RED) {
setColor(sib, BLACK);
setColor(parentOf(x), RED);
rotateRight(parentOf(x));
sib = leftOf(parentOf(x));
}
if (colorOf(rightOf(sib)) == BLACK &&
colorOf(leftOf(sib)) == BLACK) {
setColor(sib, RED);
x = parentOf(x);
} else {
if (colorOf(leftOf(sib)) == BLACK) {
setColor(rightOf(sib), BLACK);
setColor(sib, RED);
rotateLeft(sib);
sib = leftOf(parentOf(x));
}
setColor(sib, colorOf(parentOf(x)));
setColor(parentOf(x), BLACK);
setColor(leftOf(sib), BLACK);
rotateRight(parentOf(x));
x = root;
}
}
}
setColor(x, BLACK);
}
5. 序列化与反序列化
// 序列化
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// Write out the Comparator and any hidden stuff
s.defaultWriteObject();
// Write out size (number of Mappings)
s.writeInt(size);
// Write out keys and values (alternating)
// 使用迭代器迭代对 key 和 value 进行序列化
for (Iterator<Map.Entry<K,V>> i = entrySet().iterator(); i.hasNext(); ) {
Map.Entry<K,V> e = i.next();
s.writeObject(e.getKey());
s.writeObject(e.getValue());
}
}
// 反序列化
private void readObject(final java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in the Comparator and any hidden stuff
s.defaultReadObject();
// Read in size
int size = s.readInt();
// 构建树
buildFromSorted(size, null, s, null);
}
6. 迭代器
// 迭代器的基类
abstract class PrivateEntryIterator<T> implements Iterator<T> {
Entry<K,V> next;
Entry<K,V> lastReturned;
int expectedModCount;
PrivateEntryIterator(Entry<K,V> first) {
expectedModCount = modCount;
lastReturned = null;
next = first;
}
public final boolean hasNext() {
return next != null;
}
final Entry<K,V> nextEntry() {
Entry<K,V> e = next;
if (e == null)
throw new NoSuchElementException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
next = successor(e);
lastReturned = e;
return e;
}
final Entry<K,V> prevEntry() {
Entry<K,V> e = next;
if (e == null)
throw new NoSuchElementException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
next = predecessor(e);
lastReturned = e;
return e;
}
public void remove() {
if (lastReturned == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
// deleted entries are replaced by their successors
if (lastReturned.left != null && lastReturned.right != null)
next = lastReturned;
deleteEntry(lastReturned);
expectedModCount = modCount;
lastReturned = null;
}
}
final class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
EntryIterator(Entry<K,V> first) {
super(first);
}
public Map.Entry<K,V> next() {
return nextEntry();
}
}
final class ValueIterator extends PrivateEntryIterator<V> {
ValueIterator(Entry<K,V> first) {
super(first);
}
public V next() {
return nextEntry().value;
}
}
final class KeyIterator extends PrivateEntryIterator<K> {
KeyIterator(Entry<K,V> first) {
super(first);
}
public K next() {
return nextEntry().key;
}
}
final class DescendingKeyIterator extends PrivateEntryIterator<K> {
DescendingKeyIterator(Entry<K,V> first) {
super(first);
}
public K next() {
return prevEntry().key;
}
public void remove() {
if (lastReturned == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
deleteEntry(lastReturned);
lastReturned = null;
expectedModCount = modCount;
}
}
7. 总结
TreeMap 底层数据结构为红黑树(相对平衡的二叉查找树),查找的时间复杂度为 O(logN);
其他特性与 HashMap 及 HashTable 相似。
参考资料:
https://www.cnblogs.com/skywang12345/p/3245399.html
https://www.cnblogs.com/yitong0768/p/4561825.html