手撕红黑树-java版
红黑树的五个平衡条件
- 每个节点非黑即红
- 根节点是黑色
- 叶节点(即虚拟叶节点,红黑树中的叶节点指的是看不见的虚拟空节点)是黑色
- 如果一个节点是红色,则它的两个子节点都是黑色的
- 从根节点出发到所有叶节点路径上,黑色节点数量相同
红黑树最长路径是最短路径的2倍
相比于AVL树,红黑树的控制条件更加松散,为了降低在插入和删除节点后的调整次数
红黑树自平衡的三种依据
- 变色:节点的颜色由黑变红或者由红变黑
- 左旋:已某一节点作为支点(旋转节点),其右子节点变为旋转节点的父节点,右子节点的左节点变为旋转节点的右子节点,左子节点保存不变
- 右旋:已某一节点作为支点(旋转节点),其左子节点变为旋转节点的父节点,左子节点的右节点变为旋转节点的左子节点,右 子节点保存不变
调整策略
- 插入调整从祖父节点向下观察,若父节点与子节点出现问题才需要调整
- 删除节点从父节点向下观察
插入的情况
插入黑色节点,必然会调整,插入红色节点,可能会调整
所以红黑树在插入时为红色节点
情况一
当回溯到15节点时发现20节点与子节点发送冲突,这时需要调整
使用红黑黑结构代替当前的黑红红结构
这部分调整之前每条路径上黑色节点的数量,应该等于调整之后黑色节点的数量 这时调整之后对红黑树整体不受影响
处理办法:将1和20修改为黑色,15修改为红色
情况二
从20节点向下看发现20的左子节点(15)为红色,15的左子节点(10)也为红色
处理方法:将20调整为红色,15调整为黑色,从20进行右旋
或者将10改为黑色 两种方案
插入代码实现
定义的树中,为了方便实现直接使用了compareTo比较key大小,建议使用"a,b,c,d…"来排序
红黑树结构和方法定义
package RBTree;
public class RBTree<K extends Comparable<K>,V> {
private static final boolean RED = true;
private static final boolean BLACK = false;
private RBNode root;
public RBNode getRoot() {
return root;
}
public void setRoot(RBNode root) {
this.root = root;
}
private RBNode parentOf(RBNode node) {
if (node != null) {
return node.parent;
}
return null;
}
private boolean isRed(RBNode node) {
if (node != null) {
return node.color == RED;
}
return false;
}
private void setRed(RBNode node) {
if (node != null) {
node.color = RED;
}
}
private boolean isBlack(RBNode node) {
if (node != null) {
return node.color == BLACK;
}
return false;
}
private void setBlack(RBNode node) {
if (node != null) {
node.color = BLACK;
}
}
public void inOrderPrint() {
inOrderPrint(this.root);
}
public void inOrderPrint(RBNode node) {
if (node != null) {
inOrderPrint(node.left);
System.out.println("key: " + node.key + "value: " + node.value);
inOrderPrint(node.right);
}
}
public void insert(K key, V value) {
RBNode node = new RBNode();
node.setKey(key);
node.setValue(value);
node.setColor(RED);
insert(node);
}
private void insert(RBNode node) {
RBNode parent = null;
RBNode x = this.root;
while (x != null) {
parent = x;
int compareTo = node.key.compareTo(x.key);
if (compareTo > 0) {
x = x.right;
} else if (compareTo == 0) {
x.setValue(node.getValue());
return;
} else {
x = x.left;
}
}
node.parent = parent;
if (parent != null) {
int compareTo = node.key.compareTo(parent.key);
if (compareTo > 0) {
parent.right = node;
} else {
parent.left = node;
}
} else{
this.root = node;
}
insertFixUp(node);
}
private void insertFixUp(RBNode node) {
this.root.setColor(BLACK);
RBNode parent = parentOf(node);
RBNode gParent = parentOf(parent);
if (parent != null && isRed(parent)) {
RBNode uncle = null;
if (parent == gParent.left) {
uncle = gParent.right;
if (uncle != null && isRed(uncle)) {
setBlack(parent);
setBlack(uncle);
setBlack(gParent);
insertFixUp(gParent);
return;
}
if (uncle == null || isBlack(uncle)) {
if (node == parent.left) {
setBlack(parent);
setRed(gParent);
rightRotate(gParent);
return;
}
if (node == parent.right) {
leftRotate(parent);
insertFixUp(parent);
return;
}
}
} else {
uncle = gParent.left;
if (uncle != null && isRed(uncle)) {
setBlack(parent);
setBlack(uncle);
setBlack(gParent);
insertFixUp(gParent);
return;
}
if (uncle == null || isBlack(uncle)) {
if (node == parent.right) {
setBlack(parent);
setRed(gParent);
leftRotate(gParent);
return;
}
if (node == parent.left) {
rightRotate(parent);
insertFixUp(parent);
return;
}
}
}
}
}
private void leftRotate(RBNode x) {
RBNode y = x.right;
x.right = y.left;
if (y.left != null) {
y.left.parent = x;
}
if (x.parent != null) {
y.parent = x.parent;
if (x == x.parent.left) {
x.parent.left = y;
} else {
x.parent.right = y;
}
} else {
this.root = y;
this.root.parent = null;
}
x.parent = y;
y.left = x;
}
private void rightRotate(RBNode y){
RBNode x = y.left;
y.left = x.right;
if (x.right != null) {
x.right.parent = y;
}
if (y.parent != null) {
x.parent = y.parent;
if (y == y.parent.left) {
y.parent.left = x;
} else {
y.parent.right = x;
}
} else {
this.root = x;
this.root.parent = null;
}
y.parent = x;
x.right = y;
}
static class RBNode<K extends Comparable<K>,V>{
private RBNode parent;
private RBNode left;
private RBNode right;
private boolean color;
private K key;
private V value;
public RBNode() {
}
public RBNode(RBNode parent, RBNode left, RBNode right, boolean color, K key, V value) {
this.parent = parent;
this.left = left;
this.right = right;
this.color = color;
this.key = key;
this.value = value;
}
public RBNode getParent() {
return parent;
}
public void setParent(RBNode parent) {
this.parent = parent;
}
public RBNode getLeft() {
return left;
}
public void setLeft(RBNode left) {
this.left = left;
}
public RBNode getRight() {
return right;
}
public void setRight(RBNode right) {
this.right = right;
}
public boolean isColor() {
return color;
}
public void setColor(boolean color) {
this.color = color;
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
}
}
打印红黑树
引用网上源码
package RBTree;
public class TreeOperation {
public static int getTreeDepth(RBTree.RBNode root) {
return root == null ? 0 : (1 + Math.max(getTreeDepth(root.getLeft()), getTreeDepth(root.getRight())));
}
private static void writeArray(RBTree.RBNode currNode, int rowIndex, int columnIndex, String[][] res, int treeDepth) {
if (currNode == null) return;
res[rowIndex][columnIndex] = String.valueOf(currNode.getKey() + "-" + (currNode.isColor() ? "R" : "B") + "");
int currLevel = ((rowIndex + 1) / 2);
if (currLevel == treeDepth) return;
int gap = treeDepth - currLevel - 1;
if (currNode.getLeft() != null) {
res[rowIndex + 1][columnIndex - gap] = "/";
writeArray(currNode.getLeft(), rowIndex + 2, columnIndex - gap * 2, res, treeDepth);
}
if (currNode.getRight() != null) {
res[rowIndex + 1][columnIndex + gap] = "\\";
writeArray(currNode.getRight(), rowIndex + 2, columnIndex + gap * 2, res, treeDepth);
}
}
public static void show(RBTree.RBNode root) {
if (root == null) System.out.println("EMPTY!");
int treeDepth = getTreeDepth(root);
int arrayHeight = treeDepth * 2 - 1;
int arrayWidth = (2 << (treeDepth - 2)) * 3 + 1;
String[][] res = new String[arrayHeight][arrayWidth];
for (int i = 0; i < arrayHeight; i ++) {
for (int j = 0; j < arrayWidth; j ++) {
res[i][j] = " ";
}
}
writeArray(root, 0, arrayWidth/ 2, res, treeDepth);
for (String[] line: res) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < line.length; i ++) {
sb.append(line[i]);
if (line[i].length() > 1 && i <= line.length - 1) {
i += line[i].length() > 4 ? 2: line[i].length() - 1;
}
}
System.out.println(sb.toString());
}
}
}
测试
package RBTree;
import java.util.Scanner;
public class RBTreeTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
RBTree<String, Object> rbTree = new RBTree<String, Object>();
while (true) {
System.out.println("请输入key:");
String key = scanner.next();
System.out.println();
rbTree.insert(key, null);
TreeOperation.show(rbTree.getRoot());
}
}
}
|