以下是一个简单的Java代码实现红黑树的示例:
public class RedBlackTree<T extends Comparable<T>> {
private static final boolean RED = true;
private static final boolean BLACK = false;
private Node<T> root;
private static class Node<T extends Comparable<T>> {
T key;
Node<T> left, right;
boolean color;
public Node(T key, boolean color) {
this.key = key;
this.color = color;
}
}
public void insert(T key) {
root = insert(root, key);
root.color = BLACK;
}
private Node<T> insert(Node<T> node, T key) {
if (node == null) {
return new Node<>(key, RED);
}
int cmp = key.compareTo(node.key);
if (cmp < 0) {
node.left = insert(node.left, key);
} else if (cmp > 0) {
node.right = insert(node.right, key);
}
// Balance the tree using rotations and color flips
if (isRed(node.right) && !isRed(node.left)) {
node = rotateLeft(node);
}
if (isRed(node.left) && isRed(node.left.left)) {
node = rotateRight(node);
}
if (isRed(node.left) && isRed(node.right)) {
flipColors(node);
}
return node;
}
private boolean isRed(Node<T> node) {
if (node == null) {
return false;
}
return node.color == RED;
}
private Node<T> rotateLeft(Node<T> node) {
Node<T> x = node.right;
node.right = x.left;
x.left = node;
x.color = node.color;
node.color = RED;
return x;
}
private Node<T> rotateRight(Node<T> node) {
Node<T> x = node.left;
node.left = x.right;
x.right = node;
x.color = node.color;
node.color = RED;
return x;
}
private void flipColors(Node<T> node) {
node.color = RED;
node.left.color = BLACK;
node.right.color = BLACK;
}
}
该实现仅包含插入操作,其他基本操作,如删除、查找和遍历等可以通过类似的方式实现。在实际使用中,建议根据实际需要进行优化,例如添加节点数、维护树高度等。