* 修复删除后问题
*
* @param root
* @param x
* 删除时候的替换节点
*
* @return
*/
static TreeNode repairDelete(TreeNode root, TreeNode x) {
TreeNode xParent, brother;
while (true) {
if (x == null) {
return root;
}
if (x.red || x == root) {
x.red = false;
return root;
}
if ((xParent = x.parent).left == x) {
brother = xParent.right;
if (brother != null && brother.red) {
brother.red = false;
xParent.red = true;
root = rotateLeft(root, xParent);
brother = (xParent = x.parent) == null ? null : xParent.right;
}
if (brother == null) {
x = xParent;
} else {
TreeNode broLeft = brother.left, broRight = brother.right;
if ((broLeft == null || !broLeft.red) && (broRight == null || !broRight.red)) {
brother.red = true;
x = xParent;
} else {
if (broRight == null || !broRight.red) {
brother.red = true;
broLeft.red = false;
root = rotateRight(root, brother);
brother = (xParent = x.parent) == null ? null : xParent.right;
}
if (brother != null) {
brother.red = xParent.red;
if((broRight=brother.right)!=null){
broRight.red= false;
}
xParent.red = false;
root = rotateLeft(root, xParent);
x = root;
}
}
}
} else {
brother = xParent.left;
if (brother != null && brother.red) {
brother.red = false;
xParent.red = true;
root = rotateRight(root, xParent);
brother = (xParent = x.parent) == null ? null : xParent.left;
}
if (brother == null) {
x = xParent;
} else {
TreeNode broLeft = brother.left, broRight = brother.right;
if ((broLeft == null || !broLeft.red) && (broRight == null || !broRight.red)) {
brother.red = true;
x = xParent;
} else {
if (broLeft == null || !broLeft.red) {
brother.red = true;
broRight.red = false;
root = rotateLeft(root, brother);
brother = (xParent = x.parent) == null ? null : xParent.left;
}
if (brother != null) {
brother.red = xParent.red;
brother.left.red = false;
xParent.red = false;
root = rotateRight(root, xParent);
x = root;
}
}
}
}
}
}