转化为红黑树——插入
这个大佬讲的非常清晰,拜上地址:https://www.cnblogs.com/nullllun/p/8214599.html#autoid-3-2-0
简单看一下HashMap的java.util.HashMap.TreeNode#balanceInsertion就是对应上文链接中的几种插入情形,源码:
static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
TreeNode<K,V> x) {
x.red = true;
//xp:插入节点的父节点 xpp:插入节点的祖父节点
//xppl:左叔叔节点 (插入节点的祖父节点的左孩子)
//xppr:右叔叔节点 (插入节点的祖父节点的右孩子)
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);
}
}
}
}
}
}