红黑树(自顶向下)
前言
课程设计,仅供参考。
实现插入及调整和删除及调整。
具体实现流程讲解可参考下面的链接文章。
说明:提供文章的学姐与我的课程设计算法相同。
答辩幻灯片不再提供。
红黑树(自顶向下)的插入实现(C++)
红黑树–删除(自顶向下)
代码(JAVA版本)
package courseproject;
enum Color {
// 枚举,表示节点的颜色信息
RED, BLACK;
}
public class RedBlackTree<K extends Comparable<? super K>, V> {
/*
* 成员变量说明: 根节点为:root
* 当前节点,当前节点的双亲节点,当前节点的祖父节点,当前节点的曾祖父节点,分别表示为:target、parent、gparent、great
* 节点个数:size 红黑树的深度(阶度):high 默认最大。
*/
private Node<K, V> root;
private Node<K, V> great, gparent, parent, target;
private int size;
private int high = Integer.MAX_VALUE;
public int highSize() {
// 求最大高度
return highSize(root);
}
private int highSize(Node<K, V> target) {
// 递归方法求最大的深度
if (target == null)
return 0;
int left = highSize(target.left);
int right = highSize(target.right);
return left > right ? left + 1 : right + 1;
}
public int size() {
return size;
}
public RedBlackTree(int high) {
this.high = high;
}
public RedBlackTree() {
}
public boolean isEmpty() {
return size == 0;
}
private static class Node<K, V> {
K key;
@SuppressWarnings("unused")
V value;
Color color;
Node<K, V> left;
Node<K, V> right;
Node(K key, V value, Color color) {
this.key = key;
this.value = value;
this.color = color;
}
Node(K key, V value, Color color, Node<K, V> right, Node<K, V> left) {
this.key = key;
this.value = value;
this.color = color;
this.right = right;
this.left = left;
}
}
public void insert(K key, V value, Color color) {
if (high == highSize()) {
// 简单处理
System.out.println("Red——Black Tree已达到设置最大高度,插入失败!");
return;
}
if (insertSearch(key)) {
// 找到,修改原有的信息
target.color = color;
target.value = value;
insertAdjust();// 修改后可能不符合红黑树性质了,进行检查
} else {
// 没找到则插入新的节点
if (parent == null) {
// 空树
root = new Node<K, V>(key, value, Color.BLACK);
} else {
target = new Node<K, V>(key, value, color);
if (key.compareTo(parent.key) < 0)// 决定插入的结点是双亲结点的左孩子还是右孩子
parent.left = target;
else
parent.right = target;
// 处理双红子节点问题
insertAdjust();// 修改后可能不符合红黑树性质了,进行检查
}
size++;
}
}
private void rotateLeft(Node<K, V> target, Node<K, V> parent) {
// 可使用中间变量,减少代码量,增加一个Node内存开销
if (parent == null) {
root = target.right;
target.right = root.left;
root.left = target;
} else {
if (parent.left == target) {
parent.left = target.right;
target.right = parent.left.left;
parent.left.left = target;
} else {
parent.right = target.right;
target.right = parent.right.left;
parent.