转自:http://blog.sina.com.cn/s/blog_537bb50a010000it.html
续三:
====红黑树操作的实现,插入、删除、查找 (三)====
private Node getSuccessor(Node node){
if (node.rightChild != nil) return getMin(node.rightChild);
Node y = node.parent;
while((y != nil) && (y.rightChild == node)){
node = y;
y = y.parent;
}
return y;
}
private void rbDeleteAdjust(Node node){
while(node != getRoot() && node.color == true)
if(node == node.parent.leftChild){
Node y = node.parent.rightChild;
if(y.color == false){
y.color = true;
node.parent.color = false;
leftRotate(node.parent);
y = node.parent.rightChild;
}
if ((y.leftChild.color == true) && (y.rightChild.color == true)){
y.color = false;
node = node.parent;
}
else if(y.rightChild.color == true){
y.leftChild.color = true;
y.color = false;
rightRotate(y);
y = node.parent.rightChild;
}
y.color = node.parent.color;
node.parent.color = true;
y.rightChild.color = true;
leftRotate(node.parent);
node = getRoot();
}
else{
Node y = node.parent.leftChild;
if(y.color == false){
y.color = true;
node.parent.color = false;
rightRotate(node.parent);
y = node.parent.leftChild;
}
if ((y.rightChild.color == true) && (y.leftChild.color == true)){
y.color = false;
node = node.parent;
}
else if(y.leftChild.color == true){
y.rightChild.color = true;
y.color = false;
leftRotate(y);
y = node.parent.leftChild;
}
y.color = node.parent.color;
node.parent.color = true;
y.leftChild.color = true;
rightRotate(node.parent);
node = getRoot();
}
node.color = true;
}
private Node rbDelete(Node node){
Node y, x;
if ((node.leftChild == nil) || (node.rightChild == nil))
y = node;
else y = getSuccessor(node);
if (y.leftChild != nil) x = y.leftChild;
else x = y.rightChild;
x.parent = y.parent;
if (y.parent == nil) setRoot(x);
else if (y == y.parent.leftChild) y.parent.leftChild = x;
else y.parent.rightChild = x;
if(y != node) node.iData = y.iData;
if (y.color == true) rbDeleteAdjust(x);
return y;
}
public Node getRoot(){
return this.root;
}
//preOrder print the RBtree
public void preOrder(){
preOrder(this.root);
}
public void rbInsert(int i){
initNil();
Node node = new Node();
node.iData = i;
insert(node);
node.color = false;
node.leftChild = nil;
node.rightChild = nil;
rbInsertAdjust(node);
}
public Node rbDelete(int i){
Node node;
node = search(i);
if(node == null) return null;
else return (rbDelete(node));
}
public Node search(int key){
if(root == null) return null;
else{
Node current = root; // start at root
while(current.iData != key){ // while no match,
if(key < current.iData) // go left
current = current.leftChild;
else
current = current.rightChild; // or go right
if(current == nil) // if no child,
return null; // didn't find it
}
return current;
}
}
}