/**
- 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;
root = new Entry<>(key, value, null);//構造根節點,root沒有父節點,傳入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;//将紅黑樹根節點指派給parent
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();
@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
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;
}
/** From CLR */
private void fixAfterInsertion(Entry<K,V> x) {
//加入的節點預設的顔色是紅色
x.color = RED;
//情形1:新節點x是樹的根節點,沒有父節點不需要任何操作
//情形2:新節點x的父節點顔色是黑色的,不需要操作
while (x != null && x != root && x.parent.color == RED) {
//情形3:新節點的父節點顔色是紅色的
//判斷x的節點的父節點位置,是否屬于左子節點
if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
//擷取x節點的父節點的兄弟節點,上面語句已經判斷出x節點的父節點為左子節點,是以直接取右子節點
Entry<K,V> y = rightOf(parentOf(parentOf(x)));
//判斷是否x節點的父節點的兄弟節點為紅色
if (colorOf(y) == RED) {
setColor(parentOf(x), BLACK);//x節點的父節點設定為黑色
setColor(y, BLACK);//y節點的顔色設定為黑色
setColor(parentOf(parentOf(x)), RED);//x的父節點的父節點設定為紅色
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;
}