上篇介绍了红黑树的概述,这篇贴出红黑树的java实现代码。
public class RBTree<K extends Comparable<K>, V>{
private static final boolean RED = true;
private static final boolean BLACK = false;
private class Node{
public K key;
public V value;
public Node left, right;
public boolean color; //红黑树颜色区别
public Node(K key, V value){
this.key = key;
this.value = value;
left = null;
right = null;
color = RED; //插入节点时,总是先和另一节点融合,所以初始时设置为红色
}
}
private Node root;
private int size;
public RBTree(){
root = null;
size = 0;
}
//获取元素个数
public int getSize(){
return size;
}
//判断红黑树是否为空
public boolean isEmpty(){
return size == 0;
}
//判断节点的颜色是否为红色
private boolean isRed(Node node){
return node.color == RED;
}
//左旋转
private Node leftRotate(Node node){
Node x = node.right;
node.right = x.left;
x.left = node;
x.color = node.color;
node.color = RED;
return node;
}
//颜色翻转
private void flipColors(Node node){
node.color = RED;
node.left.color = BLACK;
node.right.color = BLACK;
}
//右旋转
private Node rightRotate(Node node){
Node x = node.left;
//右旋转
x.right = node;
node.left = x.right;
x.color = node.color;
node.color = RED;
return x;
}
// 向红黑树中添加新的元素(key, value)
public void add(K key, V value){
root = add(root, key, value);
root.color = BLACK; //最终的根节点为黑色的
}
// 向以node为根的红黑树中插入元素(key, value),递归算法
// 返回插入新节点后二红黑树的根
private Node add(Node node, K key, V value){
if(node == null){
size ++;
return new Node(key, value);
}
if(key.compareTo(node.key) < 0)
node.left = add(node.left, key, value);
else if(key.compareTo(node.key) > 0)
node.right = add(node.right, key, value);
else // key.compareTo(node.key) == 0
node.value = value;
if(isRed(node.right) && !isRed(node.left))
node = leftRotate(node);
if(isRed(node.left) && isRed(node.left.left))
node = rightRotate(node);
if(isRed(node.left) && isRed(node.right))
flipColors(node);
return node;
}
// 返回以node为根节点的红黑树中,key所在的节点
private Node getNode(Node node, K key){
if(node == null)
return null;
if(key.equals(node.key))
return node;
else if(key.compareTo(node.key) < 0)
return getNode(node.left, key);
else // if(key.compareTo(node.key) > 0)
return getNode(node.right, key);
}
//判断红黑树中是否包含key
public boolean contains(K key){
return getNode(root, key) != null;
}
//获取红黑树键为key的值value
public V get(K key){
Node node = getNode(root, key);
return node == null ? null : node.value;
}
//将红黑树键为key的value值设置成新的newValue值
public void set(K key, V newValue){
Node node = getNode(root, key);
if(node == null)
throw new IllegalArgumentException(key + " doesn't exist!");
node.value = newValue;
}
}