package Algorithms;
import java.security.Key;
public class RedAndBlackDelete<Key extends Comparable<Key>,Value> {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
private static final boolean RED=true;
private static final boolean BLACK=false;
private Node root;
//private class Node;
private class Node{
Key key;
Value val;
Node left,right;
int N;
boolean color;
Node(Key key,Value val,int N,boolean color){
this.key=key;
this.val=val;
this.N=N;
this.color=color;
}
}
private boolean isRed(Node x) {
if(x==null) return false;
return x.color=RED;
}
private Node rotateLeft(Node h) {
Node x=h.right;
h.right=x.left;
x.left=h;
x.color=h.color;
h.color=RED;
x.N=h.N;
h.N=size(h.left)+size(h.right)+1;
return x;
}
private Node rotateRight(Node h) {
Node x=h.left;
h.left=x.right;
x.right=h;
x.color=h.color;
h.color=RED;
x.N=h.N;
h.N=size(h.left)+size(h.right)+1;
return x;
}
public void delete(Key key) {
if(!isRed(root.left)&&!isRed(root.right))
root.color=RED;
root=delete(root,key);
if(!isEmpty()) root.color=BLACK;
}
private Node moveRedLeft(Node h) {
flipColors(h);
if(!isRed(h.right.left)) {
h.right=rotateRight(h.right);
h=rotateLeft(h);
flipColors(h);
}
return h;
}
private Node moveRedRight(Node h) {
flipColors(h);
if(isRed(h.left.left)) {
h=rotateRight(h);
}
return h;
}
private Node deleteMin(Node h) {
if(h.left==null)
return null;
if(!isRed(h.left)&&!isRed(h.left.left))
h=moveRedLeft(h);
h.left=deleteMin(h);
return balance(h);
}
private Node delete(Node h,Key key) {
if(key.compareTo(h.key)<0) {
if(!isRed(h.left)&&!isRed(h.right)) {
h=moveRedLeft(h);
h.left=delete(h.left,key);
}
}
else {
if(isRed(h.left))
h=rotateRight(h);
if(key.compareTo(h.key)==0&&(h.right==null))
return null;
if(!isRed(h.right)&&!isRed(h.right.left))
h=moveRedRight(h);
if(key.compareTo(h.key)==0) {
h.val=get(h.right,min(h.right).key);
h.key=min(h.right).key;
h.right=deleteMin(h.right);
}
else {
h.right=delete(h.right,key);
}
}
return balance(h);
}
private Node min(Node x) {
if(x.left==null) return x;
return min(x.left);
}
private Value get(Node x,Key key) {
if(x==null) return null;
int cmp=key.compareTo(x.key);
if(cmp<0) return get(x.left,key);
else if(cmp>0) return get(x.right,key);
else return x.val;
}
private Node balance(Node h) {
if(!isRed(h.right)) h=rotateRight(h);
if(isRed(h.right)&&isRed(h.left)) h=rotateLeft(h);
if(isRed(h.left)&&isRed(h.left.left)) h=rotateRight(h);
if(isRed(h.left)&&isRed(h.right)) flipColors(h);
h.N=size(h.left)+size(h.right)+1;
return h;
}
private int size( Node x) {
if(x==null) return 0;
else return x.N;
}
private void flipColors(Node h) {
h.color=RED;
h.left.color=BLACK;
h.right.color=BLACK;
}
}