红黑树
import sun.applet.Main;
import java.util.Base64;
public class RedBlackBST <Key extends Comparable<Key>,Value> {
private class Node{
Key key;
Value value;
Node left,right;
int n;
boolean color;
public Node(Key key, Value value, int n, boolean color) {
this.key = key;
this.value = value;
this.n = n;
this.color = color;
}
}
private static final boolean Red =true;
private static final boolean Black = false;
private Node root;
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=1+size(h.right)+size(h.left);
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=1+size(h.right)+size(h.left);
return x;
}
private int size(Node x){
if(x==null)
return 0;
return x.n;
}
private void flipColors(Node h){
h.color=Red;
h.left.color= Black;
h.right.color= Black;
}
public void put(Key key,Value value){
root = put(root,key,value);
root.color=Black;
}
private Node put(Node h, Key key, Value value) {
if(h==null){
return new Node(key,value,1,Red);
}
int cmp = key.compareTo(h.key);
if(cmp<0)
h.left=put(h.left,key,value);
else if(cmp>0)
h.right=put(h.right,key,value);
else
h.value=value;
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.right)+size(h.left)+1 ;
return h;
}
public Value get(Key key) {
return get(root, key);
}
private Value get(Node x, Key key) {
if (x == null)
return null;
int res = key.compareTo(x.key);
if (res == 0) {
return x.value;
} else if (res < 0)
return get(x.left, key);
else
return get(x.right, key);
}
}