用java编一个红黑树
时间: 2023-05-23 20:03:45 浏览: 91
Java实现的红黑树
5星 · 资源好评率100%
好的,请稍等,我会马上给您提供一个简单的Java实现红黑树的代码。
```
public class RedBlackTree<K extends Comparable<K>, V> {
private Node root;
private static final boolean RED = true;
private static final boolean BLACK = false;
private class Node {
K key;
V value;
Node left, right;
int size;
boolean color;
Node(K key, V value, int size, boolean color) {
this.key = key;
this.value = value;
this.size = size;
this.color = color;
}
}
public void put(K key, V value) {
root = put(root, key, value);
root.color = BLACK;
}
private Node put(Node h, K key, V 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.size = size(h.left) + size(h.right) + 1;
return h;
}
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.size = h.size;
h.size = size(h.left) + size(h.right) + 1;
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.size = h.size;
h.size = size(h.left) + size(h.right) + 1;
return x;
}
private void flipColors(Node h) {
h.color = RED;
h.left.color = BLACK;
h.right.color = BLACK;
}
private int size(Node x) {
if (x == null) return 0;
return x.size;
}
}
```
这个实现是一个基本的红黑树实现,有put方法用于插入元素,以及一些辅助的私有方法,包括rotateLeft, rotateRight, flipColors等等。请注意,这个实现可以按照任意顺序插入元素,甚至可以插入重复元素,并且在插入时会自动维护红黑树的颜色性质和大小信息。
阅读全文