package DataStructure.tree;
public class RedBlackTree<Key extends Comparable<Key>,Value>{
private Node root;
private int N;
private static final boolean Red=true;
private static final boolean Black=false;
private class Node{
public Key key;
public Value value;
public Node left;
public Node right;
public boolean color;
public Node(Key key,Value value,Node right,Node Left,boolean color){
this.key=key;
this.value=value;
this.right=right;
this.left=left;
this.color=color;
}
}
public int size(){
return N;
}
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;
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;
return x;
}
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;
}
public Node put(Node h,Key key,Value value) {
if(h==null){
N++;
return new Node(key,value,null,null,Black);
}
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);
}
return h;
}
public Value get(Key key){
return get(root,key);
}
public 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.value;
}
}
}
红黑树的实现
最新推荐文章于 2024-08-16 19:41:03 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)