红黑树是一种平衡二叉搜索树,它的每个节点都有一个颜色属性,可以是红色或黑色。为了保证红黑树的平衡,它有以下五条性质:
- 每个节点要么是红色,要么是黑色。
- 根节点是黑色。
- 叶子节点(最后一层的节点)是黑色。
- 如果一个节点是红色,则它的两个儿子都是黑色。
- 对于每个节点,从该节点到其所有后代叶节点的简单路径上,均包含相同数目的黑色节点。
下面是一个 Java 实现红黑树的例子:
```java public class RedBlackTree { private static final boolean RED = true; private static final boolean BLACK = false;
private classNode {
int key;
Node left;
Node right;
boolean color;
Node(int key, boolean color) {
this.key = key;
this.color = color;
}
}
private Node root;
private boolean isRed(Node node) {
if (node == null) {
return false;
}
return node.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 insert(int key) {
root = insert(root, key);
root.color = BLACK;
}
private Node insert(Node h, int key) {