/**
* Introduction to Algorithms, Second Edition
* 13 Red-Black Trees
*
* 红黑树的条件:
* 1.每个节点标记为“红”或“黑”。
* 2.根标记为“黑”。
* 3.所有叶节点(nil)标记为“黑”。
* 4.如果一个节点为“红”,则它的两个节点都为“黑”。
* 5.对每个的节点,从该节点至后继叶节点包含相同数量的“黑”节点。
* @author shiwenliang
*/
import java.util.ArrayList;
import java.util.List;
public class RedBlackTree {
/**
* 数据节点
*/
public static class Node {
int key;
Node parent; //父节点
Node left; //左子节点
Node right; //右子节点
Color color; //节点颜色
public Node(int key) {
this.key = key;
}
public String toString() {
return String.valueOf(key);
}
}
/**
* 颜色
*/
private enum Color { RED, BLACK};
Node root; //根节点
Node nil; //空节点
/**
* 构造函数
*/
public RedBlackTree() {
nil = new Node(-1);
nil.color = Color.BLACK;
root = nil;
}
/**
* 左旋转。
* @param x 支点
*/
private void leftRotate(Node x) {
Node y = x.right; // y是x的右子节点
x.right = y.left; // y的左子树转换成x的右子树
if (y.left != nil)
y.left.parent = x;
y.parent = x.parent; // 用y替换x的位置
if (x.parent == nil) {
root = y;
} else if (x == x.parent.left) {
x.parent.left = y;
} else {
x.parent.right = y;
}
y.left = x; // 将x设置为y的左子节点
x.parent = y;
}
/**
* 右旋转。
* @param x 支点
*/
private void rightRotate(Node y) {
Node x = y.left; // y是x的右子节点
y.left = x.right; // y的左子树转换成x的右子树
if (x.right != nil)
x.right.parent = y;
x.parent = y.parent; // 用y替换x的位置
if (y.parent == nil) {
root = x;
} else if (y == y.parent.left) {
y.parent.left = x;
} else {
y.parent.right = x;
}
x.right = y; // 将x设置为y的左子节点
y.parent = x;
}
/**
* 采用递归法查找键值为k的节点。
* @param k 节点的键值
* @return 返回键值为k的节点
*/
public Node search(int k) {
return search(root, k);
}
/**
* 采用递归法查找键值为k的节点。
* @param x 当前节点
* @param k 节点的键值
* @return 返回键值为k的节点
*/
private Node search(Node x, int k) {
if(x == nil || k == x.key) {
return x;
} else if(k < x.key) {
return search(x.left, k);
} else {
return search(x.right, k);
}
}
/**
* 采用迭代法查找键值为k的节点。
* @param x 当前节点
* @param k 节点的键值
* @return 返回键值为k的节点
*/
public Node iterativeSearch(int k) {
return iterativeSearch(root, k);
}
/**
* 采用迭代法查找键值为k的节点。
* @param x 当前节点
* @param k 节点的键值
* @return 返回键值为k的节点
*/
private Node iterativeSearch(Node x, int k) {
while(x != nil && k != x.key) {
if(k < x.key) {
x = x.left;
} else {
x = x.right;
}
}
return x;
}
/**
* 返回树的最小键值的节点。
* @return 最小键值的节点
*/
public Node minimum() {
return minimum(root);
}
/**
* 返回树的最小键值的节点。
* @param x 当前节点
* @return 最小键值的节点
*/
private Node minimum(Node x) {
while(x.left != nil) {
x = x.left;
}
return x;
}
/**
* 返回树的最大键值的节点。
* @return 最大键值的节点
*/
public Node maximum() {
return maximum(root);
}
/**
* 返回树的最大键值的节点。
* @param x 当前节点
* @return 最大键值的节点
*/
private Node maximum(Node x) {
while(x.right != nil) {
x = x.right;
}
return x;
}
/**
* 返回指定节点x的后继节点。
* @param x 当前节点
* @return x的后继节点;如果x具有最大键值,返回null
*/
public Node successor(Node x) {
if(x.right != nil) {
return minimum(x.right);
}
Node y = x.parent;
while(y != nil && x == y.right) {
x = y;
y = y.parent;
}
return y;
}
/**
* 返回指定节点x的前驱节点。
* @param x 当前节点
* @return x的前驱节点;如果x具有最小键值,返回null
*/
public Node predecessor(Node x) {
if(x.left != nil) {
return maximum(x.left);
}
Node y = x.parent;
while(y != nil && x == y.left) {
x = y;
y = y.parent;
}
return y;
}
/**
* 插入节点。
* @param z 待插入节点
*/
public void insert(Node z) {
Node y = nil; //当前节点的父节点
Node x = root; //当前节点
while(x != nil) { //迭代查寻z应该所在的位置
y = x;
if(z.key < x.key) {
x = x.left;
} else {
x = x.right;
}
}
z.parent = y;
if(y == nil) {
root = z; //如果没有父节点,则插入的节点是根节点。
} else if(z.key < y.key) {
y.left = z;
} else {
y.right = z;
}
z.left = nil;
z.right = nil;
z.color = Color.RED;
insertFixup(z);
}
/**
* 按红黑树规则进行调整。
* @param z 待插入节点
*/
public void insertFixup(Node z) {
while(z.parent.color == Color.RED) { //违反条件4,并且保证z有爷爷
if(z.parent == z.parent.parent.left) { //z的父节点是左子节点
Node y = z.parent.parent.right;
if(y.color == Color.RED) { //如果z的叔叔是红
z.parent.color = Color.BLACK; //将z的父亲和叔叔设为黑
y.color = Color.BLACK;
z.parent.parent.color = Color.RED; //z的爷爷设为红
z = z.parent.parent; //迭代
} else { //如果z的叔叔是黑
if (z == z.parent.right) { //如果z是右子节点,左旋
z = z.parent;
leftRotate(z);
}
z.parent.color = Color.BLACK; //z的父亲为黑(叔叔为黑)
z.parent.parent.color = Color.RED; //z的爷爷为红
rightRotate(z.parent.parent); // 右旋
}
} else { //z的父节点是右子节点,反向对称
Node y = z.parent.parent.left;
if(y.color == Color.RED) {
z.parent.color = Color.BLACK;
y.color = Color.BLACK;
z.parent.parent.color = Color.RED;
z = z.parent.parent;
} else {
if (z == z.parent.left) {
z = z.parent;
rightRotate(z);
}
z.parent.color = Color.BLACK;
z.parent.parent.color = Color.RED;
leftRotate(z.parent.parent);
}
}
}
root.color = Color.BLACK; //满足条件2
}
/**
* 删除节点。
* @param z 待删除节点
*/
public Node delete(Node z) {
Node y = null;
Node x = null;
if (z.left == nil || z.right == nil) {
y = z;
} else {
y = successor(z);
}
if (y.left != nil) {
x = y.left;
} else {
x = y.right;
}
x.parent = y.parent;
if (y.parent == nil) {
root = x;
} else if (y == y.parent.left) {
y.parent.left = x;
} else {
y.parent.right = x;
}
if (y != z) { //如果z包含两个子节点,用y替换z的位置
z.key = y.key;
}
if(y.color == Color.BLACK) {
deleteFixup(x);
}
return y;
}
/**
* 按红黑树规则进行调整。
* @param z 待删除节点
*/
private void deleteFixup(Node x) {
while(x != root && x.color == Color.BLACK) {
if(x == x.parent.left) {
Node w = x.parent.right;
if(w.color == Color.RED) {
w.color = Color.BLACK;
x.parent.color = Color.RED;
leftRotate(x.parent);
w = x.parent.right;
}
if(w.left.color == Color.BLACK && w.right.color == Color.BLACK) {
w.color = Color.RED;
x = x.parent;
} else {
if(w.right.color == Color.BLACK) {
w.left.color = Color.BLACK;
w.color = Color.RED;
rightRotate(w);
w = x.parent.right;
}
w.color = x.parent.color;
x.parent.color = Color.BLACK;
w.right.color = Color.BLACK;
leftRotate(x.parent);
x = root;
}
} else {
Node w = x.parent.left;
if(w.color == Color.RED) {
w.color = Color.BLACK;
x.parent.color = Color.RED;
rightRotate(x.parent);
w = x.parent.left;
}
if(w.right.color == Color.BLACK && w.left.color == Color.BLACK) {
w.color = Color.RED;
x = x.parent;
} else {
if(w.left.color == Color.BLACK) {
w.right.color = Color.BLACK;
w.color = Color.RED;
leftRotate(w);
w = x.parent.left;
//preorderWalk();
}
w.color = x.parent.color;
x.parent.color = Color.BLACK;
w.left.color = Color.BLACK;
rightRotate(x.parent);
x = root;
}
}
}
x.color = Color.BLACK;
}
/**
* 中序遍历。即从小到大排序。
* @return 返回已排序的节点列表
*/
public List<Node> inorderWalk() {
List<Node> list = new ArrayList<Node>();
inorderWalk(root, list);
return list;
}
/**
* 中序遍历。
* @param x 当前节点
* @param list 遍历结果存储在list中
*/
private void inorderWalk(Node x, List<Node> list) {
if(x != nil) {
inorderWalk(x.left, list);
list.add(x);
inorderWalk(x.right, list);
}
}
/**
* 前序遍历打印。即从小到大排序。
* @return 返回已排序的节点列表
*/
public void preorderWalk() {
preorderWalk(root);
}
/**
* 中序遍历打印。
* @param x 当前节点
* @param list 遍历结果存储在list中
*/
private void preorderWalk(Node x) {
if(x != nil) {
System.out.print("(");
System.out.print(x);
preorderWalk(x.left);
preorderWalk(x.right);
System.out.print(")");
} else {
System.out.print("N");
}
}
}
import java.util.List;
import junit.framework.TestCase;
public class RedBlackTreeTest extends TestCase {
public void testLinkedList() {
RedBlackTree tree = new RedBlackTree();
// 插入N个随机节点
int count = 100;
for (int i = 0; i < count;) {
int key = (int) (Math.random() * 100);
if (tree.search(key) == tree.nil) {
tree.insert(new RedBlackTree.Node(key));
i++;
}
}
//测试最大值,最小值
List<RedBlackTree.Node> list = tree.inorderWalk();
verifyOrdered(list);
assertEquals(count, list.size());
assertEquals(list.get(0), tree.minimum());
assertEquals(list.get(list.size() - 1), tree.maximum());
//测试后继
RedBlackTree.Node min = tree.minimum(), succ = null;
while((succ=tree.successor(min)) != tree.nil) {
assertTrue(succ.key > min.key);
min = succ;
}
//测试前驱
RedBlackTree.Node max = tree.maximum(), pre = null;
while((pre=tree.predecessor(max)) != tree.nil) {
assertTrue(succ.key < max.key);
max = pre;
}
//测试删除
int[] keys = new int[list.size()];
for(int i = 0; i < keys.length; i++) {
keys[i] = list.get(i).key;
}
PermuteBySorting.permute(keys);
for (int i = 0; i < count; i++) {
RedBlackTree.Node node = tree.search(keys[i]);
assertNotNull(node);
tree.delete(node);
assertEquals(tree.nil, tree.search(keys[i]));
verifyOrdered(tree.inorderWalk());
}
}
private boolean verifyOrdered(List<RedBlackTree.Node> list) {
for (int i = 1; i < list.size(); i++) {
if (list.get(i - 1).key > list.get(i).key) {
return false;
}
}
return true;
}
}
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
/*-----------------------------------------------------------
RB-Tree的插入和删除操作的实现算法
参考资料:
1) <<Introduction to algorithm>>
2) <<STL源码剖析>>
3) sgi-stl中stl_tree.h中的实现算法
4) http://epaperpress.com/sortsearch/index.html
5) http://www.ececs.uc.edu/~franco/C321/html/RedBlack/redblack.html
作者:李创 ( http://www.cppblog.com/converse/ )
您可以自由的传播,修改这份代码,转载处请注明原作者
红黑树的几个性质:
1) 每个结点只有红和黑两种颜色
2) 根结点是黑色的
3) 每个叶子结点(空结点被认为是叶子结点)是黑色的
4) 如果一个结点是红色的,那么它的左右两个子结点的颜色是黑色的
5) 对于每个结点而言,从这个结点到叶子结点的任何路径上的黑色结点
的数目相同
-------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef int KEY;
enum NODECOLOR
{
BLACK = 0,
RED = 1
};
typedef struct RBTree
{
struct RBTree *parent;
struct RBTree *left, *right;
KEY key;
NODECOLOR color;
}RBTree, *PRBTree;
PRBTree RB_InsertNode(PRBTree root, KEY key);
PRBTree RB_InsertNode_Fixup(PRBTree root, PRBTree z);
PRBTree RB_DeleteNode(PRBTree root, KEY key);
PRBTree RB_DeleteNode_Fixup(PRBTree root, PRBTree z);
PRBTree Find_Node(PRBTree root, KEY key);
void Left_Rotate(PRBTree A, PRBTree& root);
void Right_Rotate(PRBTree A, PRBTree& root);
void Mid_Visit(PRBTree T);
void Mid_DeleteTree(PRBTree T);
void Print_Node(PRBTree node);
/*-----------------------------------------------------------
| A B
| / / ==> / /
| a B A y
| / / / /
| b y a b
-----------------------------------------------------------*/
void Left_Rotate(PRBTree A, PRBTree& root)
{
PRBTree B;
B = A->right;
if (NULL == B)
return;
A->right = B->left;
if (NULL != B->left)
B->left->parent = A;
B->parent = A->parent;
// 这样三个判断连在一起避免了A->parent = NULL的情况
if (A == root)
{
root = B;
}
else if (A == A->parent->left)
{
A->parent->left = B;
}
else
{
A->parent->right = B;
}
B->left = A;
A->parent = B;
}
/*-----------------------------------------------------------
| A B
| / / / /
| B y ==> a A
| / / / /
|a b b y
-----------------------------------------------------------*/
void Right_Rotate(PRBTree A, PRBTree& root)
{
PRBTree B;
B = A->left;
if (NULL == B)
return;
A->left = B->right;
if (NULL != B->right)
B->right->parent = A;
B->parent = A->parent;
// 这样三个判断连在一起避免了A->parent = NULL的情况
if (A == root)
{
root = B;
}
else if (A == A->parent->left)
{
A->parent->left = B;
}
else
{
A->parent->right = B;
}
A->parent = B;
B->right = A;
}
/*-----------------------------------------------------------
| 函数作用:查找key值对应的结点指针
| 输入参数:根节点root,待查找关键值key
| 返回参数:如果找到返回结点指针,否则返回NULL
-------------------------------------------------------------*/
PRBTree Find_Node(PRBTree root, KEY key)
{
PRBTree x;
// 找到key所在的node
x = root;
do
{
if (key == x->key)
break;
if (key < x->key)
{
if (NULL != x->left)
x = x->left;
else
break;
}
else
{
if (NULL != x->right)
x = x->right;
else
break;
}
} while (NULL != x);
return x;
}
/*-----------------------------------------------------------
| 函数作用:在树中插入key值
| 输入参数:根节点root,待插入结点的关键值key
| 返回参数:根节点root
-------------------------------------------------------------*/
PRBTree RB_InsertNode(PRBTree root, KEY key)
{
PRBTree x, y;
PRBTree z;
if (NULL == (z = (PRBTree)malloc(sizeof(RBTree))))
{
printf("Memory alloc error/n");
return NULL;
}
z->key = key;
// 得到z的父节点
x = root, y = NULL;
while (NULL != x)
{
y = x;
if (z->key < x->key)
{
if (NULL != x->left)
{
x = x->left;
}
else
{
break;
}
}
else
{
if (NULL != x->right)
{
x = x->right;
}
else
{
break;
}
}
}
// 把z放到合适的位置
z->parent = y;
if (NULL == y)
{
root = z;
}
else
{
if (z->key < y->key)
y->left = z;
else
y->right = z;
}
// 设置z的左右子树为空并且颜色是red,注意新插入的节点颜色都是red
z->left = z->right = NULL;
z->color = RED;
// 对红黑树进行修正
return RB_InsertNode_Fixup(root, z);
}
/*-----------------------------------------------------------
| 函数作用:对插入key值之后的树进行修正
| 输入参数:根节点root,插入的结点z
| 返回参数:根节点root
-------------------------------------------------------------*/
PRBTree RB_InsertNode_Fixup(PRBTree root, PRBTree z)
{
PRBTree y;
while (root != z && RED == z->parent->color) // 当z不是根同时父节点的颜色是red
{
if (z->parent == z->parent->parent->left) // 父节点是祖父节点的左子树
{
y = z->parent->parent->right; // y为z的伯父节点
if (NULL != y && RED == y->color) // 伯父节点存在且颜色是red
{
z->parent->color = BLACK; // 更改z的父节点颜色是B
y->color = BLACK; // 更改z的伯父节点颜色是B
z->parent->parent->color = RED; // 更改z的祖父节点颜色是B
z = z->parent->parent; // 更新z为它的祖父节点
}
else // 无伯父节点或者伯父节点颜色是b
{
if (z == z->parent->right) // 如果新节点是父节点的右子树
{
z = z->parent;
Left_Rotate(z, root);
}
z->parent->color = BLACK; // 改变父节点颜色是B
z->parent->parent->color = RED; // 改变祖父节点颜色是R
Right_Rotate(z->parent->parent, root);
}
}
else // 父节点为祖父节点的右子树
{
y = z->parent->parent->left; // y为z的伯父节点
if (NULL != y && RED == y->color) // 如果y的颜色是red
{
z->parent->color = BLACK; // 更改父节点的颜色为B
y->color = BLACK; // 更改伯父节点的颜色是B
z->parent->parent->color = RED; // 更改祖父节点颜色是R
z = z->parent->parent; // 更改z指向祖父节点
}
else // y不存在或者颜色是B
{
if (z == z->parent->left) // 如果是父节点的左子树
{
z = z->parent;
Right_Rotate(z, root);
}
z->parent->color = BLACK; // 改变父节点的颜色是B
z->parent->parent->color = RED; // 改变祖父节点的颜色是RED
Left_Rotate(z->parent->parent, root);
}
}
} // while(RED == z->parent->color)
// 根节点的颜色始终都是B
root->color = BLACK;
return root;
}
/*-----------------------------------------------------------
| 函数作用:在树中删除key值
| 输入参数:根节点root,待插入结点的关键值key
| 返回参数:根节点root
-------------------------------------------------------------*/
PRBTree RB_DeleteNode(PRBTree root, KEY key)
{
PRBTree x, y, z, x_parent;
z = Find_Node(root, key);
if (NULL == z)
return root;
// 当z有一个空子树的时候,y == z
// 否则,y是大于z最小的结点
if (NULL == z->left || NULL == z->right)
y = z;
else
{
y = z->right;
while (NULL != y->left)
y = y->left;
}
// x是y的子树,可能为NULL
if (NULL != y->left)
x = y->left;
else
x = y->right;
// 设定x的位置取代y
if (NULL != x)
x->parent = y->parent;
if (NULL == y->parent)
root = x;
else if (y == y->parent->left)
y->parent->left = x;
else
y->parent->right = x;
// 把y的key拷贝到z中,这样y就是待删除的结点了
if (y != z)
{
z->key = y->key;
}
// 如果y的颜色值是B,那么要对树进行修正
if (BLACK == y->color && NULL != x)
RB_DeleteNode_Fixup(root, x);
free(y);
return root;
}
/*-----------------------------------------------------------
| 函数作用:对删除key值之后的树进行修正
| 输入参数:根节点root,删除的结点的子结点x
| 返回参数:根节点root
-------------------------------------------------------------*/
PRBTree RB_DeleteNode_Fixup(PRBTree root, PRBTree x)
{
PRBTree w;
while (x != root && BLACK == x->color)
{
if (x == x->parent->left) // 如果x是左子树
{
w = x->parent->right; // w是x的兄弟结点
if (NULL == w)
continue;
if (RED == w->color) // 如果w的颜色是红色
{
w->color = BLACK;
x->parent->color = RED;
Left_Rotate(x->parent, root);
w = x->parent->right;
}
if (NULL != w->left && BLACK == w->left->color &&
NULL != w->right && BLACK == w->right->color)
{
w->color = RED;
x = x->parent;
}
else
{
if (NULL != w->right && BLACK == w->right->color)
{
w->left->color = BLACK;
w->color = RED;
Right_Rotate(w, root);
w = x->parent->right;
}
w->color = x->parent->color;
x->parent->color = BLACK;
w->right->color = BLACK;
Left_Rotate(x->parent, root);
x = root;
}
}
else
{
w = x->parent->left;
if (NULL == w)
continue;
if (RED == w->color)
{
w->color = BLACK;
x->parent->color = RED;
Left_Rotate(x->parent, root);
w = x->parent->left;
}
if (NULL != w->left && BLACK == w->left->color &&
NULL != w->right && BLACK == w->right->color)
{
w->color = RED;
x = x->parent;
}
else
{
if (NULL != w->left && BLACK == w->left->color)
{
w->right->color = BLACK;
w->color = RED;
Left_Rotate(w, root);
w = x->parent->left;
}
w->color = x->parent->color;
x->parent->color = BLACK;
w->left->color = BLACK;
Right_Rotate(x->parent, root);
x = root;
}
}
}
x->color = BLACK;
return root;
}
void Print_Node(PRBTree node)
{
char* color[] = {"BLACK", "RED"};
printf("Key = %d,/tcolor = %s", node->key, color[node->color]);
if (NULL != node->parent)
printf(",/tparent = %d", node->parent->key);
if (NULL != node->left)
printf(",/tleft = %d", node->left->key);
if (NULL != node->right)
printf(",/tright = %d", node->right->key);
printf("/n");
}
// 中序遍历树
void Mid_Visit(PRBTree T)
{
if (NULL != T)
{
if (NULL != T->left)
Mid_Visit(T->left);
Print_Node(T);
if (NULL != T->right)
Mid_Visit(T->right);
}
}
// 中序删除树的各个节点
void Mid_DeleteTree(PRBTree T)
{
if (NULL != T)
{
if (NULL != T->left)
Mid_DeleteTree(T->left);
PRBTree temp = T->right;
free(T);
T = NULL;
if (NULL != temp)
Mid_DeleteTree(temp);
}
}
void Create_New_Array(int array[], int length)
{
for (int i = 0; i < length; i++)
{
array[i] = rand() % 256;
}
}
int main(int argc, char *argv[])
{
//int array[10] = {80, 116, 81, 205, 82, 68, 151, 20, 109, 100};
int array[10];
srand(time(NULL));
Create_New_Array(array, 10);
PRBTree root = NULL;
int i;
for (i = 0; i < 10; i++)
{
root = RB_InsertNode(root, array[i]);
}
Mid_Visit(root);
// 随机删除一个结点
int index = rand() % 10;
printf("delete node %d/n", array[index]);
root = RB_DeleteNode(root, array[index]);
Mid_Visit(root);
// 删除整颗树
Mid_DeleteTree(root);
return 0;
}
**
* Introduction to Algorithms, Second Edition
* 13 Red-Black Trees
*
* 红黑树的条件:
* 1.每个节点标记为“红”或“黑”。
* 2.根标记为“黑”。
* 3.所有叶节点(nil)标记为“黑”。
* 4.如果一个节点为“红”,则它的两个节点都为“黑”。
* 5.对每个的节点,从该节点至后继叶节点包含相同数量的“黑”节点。
* @author 土豆爸爸
*
*/
import java.util.ArrayList;
import java.util.List;
public class RedBlackTree {
/**
* 数据节点
*/
public static class Node {
int key;
Node parent; //父节点
Node left; //左子节点
Node right; //右子节点
Color color; //节点颜色
public Node(int key) {
this.key = key;
}
public String toString() {
return String.valueOf(key);
}
}
/**
* 颜色
*/
private enum Color { RED, BLACK};
Node root; //根节点
Node nil; //空节点
/**
* 构造函数
*/
public RedBlackTree() {
nil = new Node(-1);
nil.color = Color.BLACK;
root = nil;
}
/**
* 左旋转。
* @param x 支点
*/
private void leftRotate(Node x) {
Node y = x.right; // y是x的右子节点
x.right = y.left; // y的左子树转换成x的右子树
if (y.left != nil)
y.left.parent = x;
y.parent = x.parent; // 用y替换x的位置
if (x.parent == nil) {
root = y;
} else if (x == x.parent.left) {
x.parent.left = y;
} else {
x.parent.right = y;
}
y.left = x; // 将x设置为y的左子节点
x.parent = y;
}
/**
* 右旋转。
* @param x 支点
*/
private void rightRotate(Node y) {
Node x = y.left; // y是x的右子节点
y.left = x.right; // y的左子树转换成x的右子树
if (x.right != nil)
x.right.parent = y;
x.parent = y.parent; // 用y替换x的位置
if (y.parent == nil) {
root = x;
} else if (y == y.parent.left) {
y.parent.left = x;
} else {
y.parent.right = x;
}
x.right = y; // 将x设置为y的左子节点
y.parent = x;
}
/**
* 采用递归法查找键值为k的节点。
* @param k 节点的键值
* @return 返回键值为k的节点
*/
public Node search(int k) {
return search(root, k);
}
/**
* 采用递归法查找键值为k的节点。
* @param x 当前节点
* @param k 节点的键值
* @return 返回键值为k的节点
*/
private Node search(Node x, int k) {
if(x == nil || k == x.key) {
return x;
} else if(k < x.key) {
return search(x.left, k);
} else {
return search(x.right, k);
}
}
/**
* 采用迭代法查找键值为k的节点。
* @param x 当前节点
* @param k 节点的键值
* @return 返回键值为k的节点
*/
public Node iterativeSearch(int k) {
return iterativeSearch(root, k);
}
/**
* 采用迭代法查找键值为k的节点。
* @param x 当前节点
* @param k 节点的键值
* @return 返回键值为k的节点
*/
private Node iterativeSearch(Node x, int k) {
while(x != nil && k != x.key) {
if(k < x.key) {
x = x.left;
} else {
x = x.right;
}
}
return x;
}
/**
* 返回树的最小键值的节点。
* @return 最小键值的节点
*/
public Node minimum() {
return minimum(root);
}
/**
* 返回树的最小键值的节点。
* @param x 当前节点
* @return 最小键值的节点
*/
private Node minimum(Node x) {
while(x.left != nil) {
x = x.left;
}
return x;
}
/**
* 返回树的最大键值的节点。
* @return 最大键值的节点
*/
public Node maximum() {
return maximum(root);
}
/**
* 返回树的最大键值的节点。
* @param x 当前节点
* @return 最大键值的节点
*/
private Node maximum(Node x) {
while(x.right != nil) {
x = x.right;
}
return x;
}
/**
* 返回指定节点x的后继节点。
* @param x 当前节点
* @return x的后继节点;如果x具有最大键值,返回null
*/
public Node successor(Node x) {
if(x.right != nil) {
return minimum(x.right);
}
Node y = x.parent;
while(y != nil && x == y.right) {
x = y;
y = y.parent;
}
return y;
}
/**
* 返回指定节点x的前驱节点。
* @param x 当前节点
* @return x的前驱节点;如果x具有最小键值,返回null
*/
public Node predecessor(Node x) {
if(x.left != nil) {
return maximum(x.left);
}
Node y = x.parent;
while(y != nil && x == y.left) {
x = y;
y = y.parent;
}
return y;
}
/**
* 插入节点。
* @param z 待插入节点
*/
public void insert(Node z) {
Node y = nil; //当前节点的父节点
Node x = root; //当前节点
while(x != nil) { //迭代查寻z应该所在的位置
y = x;
if(z.key < x.key) {
x = x.left;
} else {
x = x.right;
}
}
z.parent = y;
if(y == nil) {
root = z; //如果没有父节点,则插入的节点是根节点。
} else if(z.key < y.key) {
y.left = z;
} else {
y.right = z;
}
z.left = nil;
z.right = nil;
z.color = Color.RED;
insertFixup(z);
}
/**
* 按红黑树规则进行调整。
* @param z 待插入节点
*/
public void insertFixup(Node z) {
while(z.parent.color == Color.RED) { //违反条件4,并且保证z有爷爷
if(z.parent == z.parent.parent.left) { //z的父节点是左子节点
Node y = z.parent.parent.right;
if(y.color == Color.RED) { //如果z的叔叔是红
z.parent.color = Color.BLACK; //将z的父亲和叔叔设为黑
y.color = Color.BLACK;
z.parent.parent.color = Color.RED; //z的爷爷设为红
z = z.parent.parent; //迭代
} else { //如果z的叔叔是黑
if (z == z.parent.right) { //如果z是右子节点,左旋
z = z.parent;
leftRotate(z);
}
z.parent.color = Color.BLACK; //z的父亲为黑(叔叔为黑)
z.parent.parent.color = Color.RED; //z的爷爷为红
rightRotate(z.parent.parent); // 右旋
}
} else { //z的父节点是右子节点,反向对称
Node y = z.parent.parent.left;
if(y.color == Color.RED) {
z.parent.color = Color.BLACK;
y.color = Color.BLACK;
z.parent.parent.color = Color.RED;
z = z.parent.parent;
} else {
if (z == z.parent.left) {
z = z.parent;
rightRotate(z);
}
z.parent.color = Color.BLACK;
z.parent.parent.color = Color.RED;
leftRotate(z.parent.parent);
}
}
}
root.color = Color.BLACK; //满足条件2
}
/**
* 删除节点。
* @param z 待删除节点
*/
public Node delete(Node z) {
Node y = null;
Node x = null;
if (z.left == nil || z.right == nil) {
y = z;
} else {
y = successor(z);
}
if (y.left != nil) {
x = y.left;
} else {
x = y.right;
}
x.parent = y.parent;
if (y.parent == nil) {
root = x;
} else if (y == y.parent.left) {
y.parent.left = x;
} else {
y.parent.right = x;
}
if (y != z) { //如果z包含两个子节点,用y替换z的位置
z.key = y.key;
}
if(y.color == Color.BLACK) {
deleteFixup(x);
}
return y;
}
/**
* 按红黑树规则进行调整。
* @param z 待删除节点
*/
private void deleteFixup(Node x) {
while(x != root && x.color == Color.BLACK) {
if(x == x.parent.left) {
Node w = x.parent.right;
if(w.color == Color.RED) {
w.color = Color.BLACK;
x.parent.color = Color.RED;
leftRotate(x.parent);
w = x.parent.right;
}
if(w.left.color == Color.BLACK && w.right.color == Color.BLACK) {
w.color = Color.RED;
x = x.parent;
} else {
if(w.right.color == Color.BLACK) {
w.left.color = Color.BLACK;
w.color = Color.RED;
rightRotate(w);
w = x.parent.right;
}
w.color = x.parent.color;
x.parent.color = Color.BLACK;
w.right.color = Color.BLACK;
leftRotate(x.parent);
x = root;
}
} else {
Node w = x.parent.left;
if(w.color == Color.RED) {
w.color = Color.BLACK;
x.parent.color = Color.RED;
rightRotate(x.parent);
w = x.parent.left;
}
if(w.right.color == Color.BLACK && w.left.color == Color.BLACK) {
w.color = Color.RED;
x = x.parent;
} else {
if(w.left.color == Color.BLACK) {
w.right.color = Color.BLACK;
w.color = Color.RED;
leftRotate(w);
w = x.parent.left;
//preorderWalk();
}
w.color = x.parent.color;
x.parent.color = Color.BLACK;
w.left.color = Color.BLACK;
rightRotate(x.parent);
x = root;
}
}
}
x.color = Color.BLACK;
}
/**
* 中序遍历。即从小到大排序。
* @return 返回已排序的节点列表
*/
public List<Node> inorderWalk() {
List<Node> list = new ArrayList<Node>();
inorderWalk(root, list);
return list;
}
/**
* 中序遍历。
* @param x 当前节点
* @param list 遍历结果存储在list中
*/
private void inorderWalk(Node x, List<Node> list) {
if(x != nil) {
inorderWalk(x.left, list);
list.add(x);
inorderWalk(x.right, list);
}
}
/**
* 前序遍历打印。即从小到大排序。
* @return 返回已排序的节点列表
*/
public void preorderWalk() {
preorderWalk(root);
}
/**
* 中序遍历打印。
* @param x 当前节点
* @param list 遍历结果存储在list中
*/
private void preorderWalk(Node x) {
if(x != nil) {
System.out.print("(");
System.out.print(x);
preorderWalk(x.left);
preorderWalk(x.right);
System.out.print(")");
} else {
System.out.print("N");
}
}
}
import java.util.List;
import junit.framework.TestCase;
public class RedBlackTreeTest extends TestCase {
public void testLinkedList() {
RedBlackTree tree = new RedBlackTree();
// 插入N个随机节点
int count = 100;
for (int i = 0; i < count;) {
int key = (int) (Math.random() * 100);
if (tree.search(key) == tree.nil) {
tree.insert(new RedBlackTree.Node(key));
i++;
}
}
//测试最大值,最小值
List<RedBlackTree.Node> list = tree.inorderWalk();
verifyOrdered(list);
assertEquals(count, list.size());
assertEquals(list.get(0), tree.minimum());
assertEquals(list.get(list.size() - 1), tree.maximum());
//测试后继
RedBlackTree.Node min = tree.minimum(), succ = null;
while((succ=tree.successor(min)) != tree.nil) {
assertTrue(succ.key > min.key);
min = succ;
}
//测试前驱
RedBlackTree.Node max = tree.maximum(), pre = null;
while((pre=tree.predecessor(max)) != tree.nil) {
assertTrue(succ.key < max.key);
max = pre;
}
//测试删除
int[] keys = new int[list.size()];
for(int i = 0; i < keys.length; i++) {
keys[i] = list.get(i).key;
}
PermuteBySorting.permute(keys);
for (int i = 0; i < count; i++) {
RedBlackTree.Node node = tree.search(keys[i]);
assertNotNull(node);
tree.delete(node);
assertEquals(tree.nil, tree.search(keys[i]));
verifyOrdered(tree.inorderWalk());
}
}
private boolean verifyOrdered(List<RedBlackTree.Node> list) {
for (int i = 1; i < list.size(); i++) {
if (list.get(i - 1).key > list.get(i).key) {
return false;
}
}
return true;
}
}
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
/*-----------------------------------------------------------
RB-Tree的插入和删除操作的实现算法
参考资料:
1) <<Introduction to algorithm>>
2) <<STL源码剖析>>
3) sgi-stl中stl_tree.h中的实现算法
4) http://epaperpress.com/sortsearch/index.html
5) http://www.ececs.uc.edu/~franco/C321/html/RedBlack/redblack.html
作者:李创 ( http://www.cppblog.com/converse/ )
您可以自由的传播,修改这份代码,转载处请注明原作者
红黑树的几个性质:
1) 每个结点只有红和黑两种颜色
2) 根结点是黑色的
3) 每个叶子结点(空结点被认为是叶子结点)是黑色的
4) 如果一个结点是红色的,那么它的左右两个子结点的颜色是黑色的
5) 对于每个结点而言,从这个结点到叶子结点的任何路径上的黑色结点
的数目相同
-------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef int KEY;
enum NODECOLOR
{
BLACK = 0,
RED = 1
};
typedef struct RBTree
{
struct RBTree *parent;
struct RBTree *left, *right;
KEY key;
NODECOLOR color;
}RBTree, *PRBTree;
PRBTree RB_InsertNode(PRBTree root, KEY key);
PRBTree RB_InsertNode_Fixup(PRBTree root, PRBTree z);
PRBTree RB_DeleteNode(PRBTree root, KEY key);
PRBTree RB_DeleteNode_Fixup(PRBTree root, PRBTree z);
PRBTree Find_Node(PRBTree root, KEY key);
void Left_Rotate(PRBTree A, PRBTree& root);
void Right_Rotate(PRBTree A, PRBTree& root);
void Mid_Visit(PRBTree T);
void Mid_DeleteTree(PRBTree T);
void Print_Node(PRBTree node);
/*-----------------------------------------------------------
| A B
| / / ==> / /
| a B A y
| / / / /
| b y a b
-----------------------------------------------------------*/
void Left_Rotate(PRBTree A, PRBTree& root)
{
PRBTree B;
B = A->right;
if (NULL == B)
return;
A->right = B->left;
if (NULL != B->left)
B->left->parent = A;
B->parent = A->parent;
// 这样三个判断连在一起避免了A->parent = NULL的情况
if (A == root)
{
root = B;
}
else if (A == A->parent->left)
{
A->parent->left = B;
}
else
{
A->parent->right = B;
}
B->left = A;
A->parent = B;
}
/*-----------------------------------------------------------
| A B
| / / / /
| B y ==> a A
| / / / /
|a b b y
-----------------------------------------------------------*/
void Right_Rotate(PRBTree A, PRBTree& root)
{
PRBTree B;
B = A->left;
if (NULL == B)
return;
A->left = B->right;
if (NULL != B->right)
B->right->parent = A;
B->parent = A->parent;
// 这样三个判断连在一起避免了A->parent = NULL的情况
if (A == root)
{
root = B;
}
else if (A == A->parent->left)
{
A->parent->left = B;
}
else
{
A->parent->right = B;
}
A->parent = B;
B->right = A;
}
/*-----------------------------------------------------------
| 函数作用:查找key值对应的结点指针
| 输入参数:根节点root,待查找关键值key
| 返回参数:如果找到返回结点指针,否则返回NULL
-------------------------------------------------------------*/
PRBTree Find_Node(PRBTree root, KEY key)
{
PRBTree x;
// 找到key所在的node
x = root;
do
{
if (key == x->key)
break;
if (key < x->key)
{
if (NULL != x->left)
x = x->left;
else
break;
}
else
{
if (NULL != x->right)
x = x->right;
else
break;
}
} while (NULL != x);
return x;
}
/*-----------------------------------------------------------
| 函数作用:在树中插入key值
| 输入参数:根节点root,待插入结点的关键值key
| 返回参数:根节点root
-------------------------------------------------------------*/
PRBTree RB_InsertNode(PRBTree root, KEY key)
{
PRBTree x, y;
PRBTree z;
if (NULL == (z = (PRBTree)malloc(sizeof(RBTree))))
{
printf("Memory alloc error/n");
return NULL;
}
z->key = key;
// 得到z的父节点
x = root, y = NULL;
while (NULL != x)
{
y = x;
if (z->key < x->key)
{
if (NULL != x->left)
{
x = x->left;
}
else
{
break;
}
}
else
{
if (NULL != x->right)
{
x = x->right;
}
else
{
break;
}
}
}
// 把z放到合适的位置
z->parent = y;
if (NULL == y)
{
root = z;
}
else
{
if (z->key < y->key)
y->left = z;
else
y->right = z;
}
// 设置z的左右子树为空并且颜色是red,注意新插入的节点颜色都是red
z->left = z->right = NULL;
z->color = RED;
// 对红黑树进行修正
return RB_InsertNode_Fixup(root, z);
}
/*-----------------------------------------------------------
| 函数作用:对插入key值之后的树进行修正
| 输入参数:根节点root,插入的结点z
| 返回参数:根节点root
-------------------------------------------------------------*/
PRBTree RB_InsertNode_Fixup(PRBTree root, PRBTree z)
{
PRBTree y;
while (root != z && RED == z->parent->color) // 当z不是根同时父节点的颜色是red
{
if (z->parent == z->parent->parent->left) // 父节点是祖父节点的左子树
{
y = z->parent->parent->right; // y为z的伯父节点
if (NULL != y && RED == y->color) // 伯父节点存在且颜色是red
{
z->parent->color = BLACK; // 更改z的父节点颜色是B
y->color = BLACK; // 更改z的伯父节点颜色是B
z->parent->parent->color = RED; // 更改z的祖父节点颜色是B
z = z->parent->parent; // 更新z为它的祖父节点
}
else // 无伯父节点或者伯父节点颜色是b
{
if (z == z->parent->right) // 如果新节点是父节点的右子树
{
z = z->parent;
Left_Rotate(z, root);
}
z->parent->color = BLACK; // 改变父节点颜色是B
z->parent->parent->color = RED; // 改变祖父节点颜色是R
Right_Rotate(z->parent->parent, root);
}
}
else // 父节点为祖父节点的右子树
{
y = z->parent->parent->left; // y为z的伯父节点
if (NULL != y && RED == y->color) // 如果y的颜色是red
{
z->parent->color = BLACK; // 更改父节点的颜色为B
y->color = BLACK; // 更改伯父节点的颜色是B
z->parent->parent->color = RED; // 更改祖父节点颜色是R
z = z->parent->parent; // 更改z指向祖父节点
}
else // y不存在或者颜色是B
{
if (z == z->parent->left) // 如果是父节点的左子树
{
z = z->parent;
Right_Rotate(z, root);
}
z->parent->color = BLACK; // 改变父节点的颜色是B
z->parent->parent->color = RED; // 改变祖父节点的颜色是RED
Left_Rotate(z->parent->parent, root);
}
}
} // while(RED == z->parent->color)
// 根节点的颜色始终都是B
root->color = BLACK;
return root;
}
/*-----------------------------------------------------------
| 函数作用:在树中删除key值
| 输入参数:根节点root,待插入结点的关键值key
| 返回参数:根节点root
-------------------------------------------------------------*/
PRBTree RB_DeleteNode(PRBTree root, KEY key)
{
PRBTree x, y, z, x_parent;
z = Find_Node(root, key);
if (NULL == z)
return root;
// 当z有一个空子树的时候,y == z
// 否则,y是大于z最小的结点
if (NULL == z->left || NULL == z->right)
y = z;
else
{
y = z->right;
while (NULL != y->left)
y = y->left;
}
// x是y的子树,可能为NULL
if (NULL != y->left)
x = y->left;
else
x = y->right;
// 设定x的位置取代y
if (NULL != x)
x->parent = y->parent;
if (NULL == y->parent)
root = x;
else if (y == y->parent->left)
y->parent->left = x;
else
y->parent->right = x;
// 把y的key拷贝到z中,这样y就是待删除的结点了
if (y != z)
{
z->key = y->key;
}
// 如果y的颜色值是B,那么要对树进行修正
if (BLACK == y->color && NULL != x)
RB_DeleteNode_Fixup(root, x);
free(y);
return root;
}
/*-----------------------------------------------------------
| 函数作用:对删除key值之后的树进行修正
| 输入参数:根节点root,删除的结点的子结点x
| 返回参数:根节点root
-------------------------------------------------------------*/
PRBTree RB_DeleteNode_Fixup(PRBTree root, PRBTree x)
{
PRBTree w;
while (x != root && BLACK == x->color)
{
if (x == x->parent->left) // 如果x是左子树
{
w = x->parent->right; // w是x的兄弟结点
if (NULL == w)
continue;
if (RED == w->color) // 如果w的颜色是红色
{
w->color = BLACK;
x->parent->color = RED;
Left_Rotate(x->parent, root);
w = x->parent->right;
}
if (NULL != w->left && BLACK == w->left->color &&
NULL != w->right && BLACK == w->right->color)
{
w->color = RED;
x = x->parent;
}
else
{
if (NULL != w->right && BLACK == w->right->color)
{
w->left->color = BLACK;
w->color = RED;
Right_Rotate(w, root);
w = x->parent->right;
}
w->color = x->parent->color;
x->parent->color = BLACK;
w->right->color = BLACK;
Left_Rotate(x->parent, root);
x = root;
}
}
else
{
w = x->parent->left;
if (NULL == w)
continue;
if (RED == w->color)
{
w->color = BLACK;
x->parent->color = RED;
Left_Rotate(x->parent, root);
w = x->parent->left;
}
if (NULL != w->left && BLACK == w->left->color &&
NULL != w->right && BLACK == w->right->color)
{
w->color = RED;
x = x->parent;
}
else
{
if (NULL != w->left && BLACK == w->left->color)
{
w->right->color = BLACK;
w->color = RED;
Left_Rotate(w, root);
w = x->parent->left;
}
w->color = x->parent->color;
x->parent->color = BLACK;
w->left->color = BLACK;
Right_Rotate(x->parent, root);
x = root;
}
}
}
x->color = BLACK;
return root;
}
void Print_Node(PRBTree node)
{
char* color[] = {"BLACK", "RED"};
printf("Key = %d,/tcolor = %s", node->key, color[node->color]);
if (NULL != node->parent)
printf(",/tparent = %d", node->parent->key);
if (NULL != node->left)
printf(",/tleft = %d", node->left->key);
if (NULL != node->right)
printf(",/tright = %d", node->right->key);
printf("/n");
}
// 中序遍历树
void Mid_Visit(PRBTree T)
{
if (NULL != T)
{
if (NULL != T->left)
Mid_Visit(T->left);
Print_Node(T);
if (NULL != T->right)
Mid_Visit(T->right);
}
}
// 中序删除树的各个节点
void Mid_DeleteTree(PRBTree T)
{
if (NULL != T)
{
if (NULL != T->left)
Mid_DeleteTree(T->left);
PRBTree temp = T->right;
free(T);
T = NULL;
if (NULL != temp)
Mid_DeleteTree(temp);
}
}
void Create_New_Array(int array[], int length)
{
for (int i = 0; i < length; i++)
{
array[i] = rand() % 256;
}
}
int main(int argc, char *argv[])
{
//int array[10] = {80, 116, 81, 205, 82, 68, 151, 20, 109, 100};
int array[10];
srand(time(NULL));
Create_New_Array(array, 10);
PRBTree root = NULL;
int i;
for (i = 0; i < 10; i++)
{
root = RB_InsertNode(root, array[i]);
}
Mid_Visit(root);
// 随机删除一个结点
int index = rand() % 10;
printf("delete node %d/n", array[index]);
root = RB_DeleteNode(root, array[index]);
Mid_Visit(root);
// 删除整颗树
Mid_DeleteTree(root);
return 0;
}
* Introduction to Algorithms, Second Edition
* 13 Red-Black Trees
*
* 红黑树的条件:
* 1.每个节点标记为“红”或“黑”。
* 2.根标记为“黑”。
* 3.所有叶节点(nil)标记为“黑”。
* 4.如果一个节点为“红”,则它的两个节点都为“黑”。
* 5.对每个的节点,从该节点至后继叶节点包含相同数量的“黑”节点。
* @author shiwenliang
*/
import java.util.ArrayList;
import java.util.List;
public class RedBlackTree {
/**
* 数据节点
*/
public static class Node {
int key;
Node parent; //父节点
Node left; //左子节点
Node right; //右子节点
Color color; //节点颜色
public Node(int key) {
this.key = key;
}
public String toString() {
return String.valueOf(key);
}
}
/**
* 颜色
*/
private enum Color { RED, BLACK};
Node root; //根节点
Node nil; //空节点
/**
* 构造函数
*/
public RedBlackTree() {
nil = new Node(-1);
nil.color = Color.BLACK;
root = nil;
}
/**
* 左旋转。
* @param x 支点
*/
private void leftRotate(Node x) {
Node y = x.right; // y是x的右子节点
x.right = y.left; // y的左子树转换成x的右子树
if (y.left != nil)
y.left.parent = x;
y.parent = x.parent; // 用y替换x的位置
if (x.parent == nil) {
root = y;
} else if (x == x.parent.left) {
x.parent.left = y;
} else {
x.parent.right = y;
}
y.left = x; // 将x设置为y的左子节点
x.parent = y;
}
/**
* 右旋转。
* @param x 支点
*/
private void rightRotate(Node y) {
Node x = y.left; // y是x的右子节点
y.left = x.right; // y的左子树转换成x的右子树
if (x.right != nil)
x.right.parent = y;
x.parent = y.parent; // 用y替换x的位置
if (y.parent == nil) {
root = x;
} else if (y == y.parent.left) {
y.parent.left = x;
} else {
y.parent.right = x;
}
x.right = y; // 将x设置为y的左子节点
y.parent = x;
}
/**
* 采用递归法查找键值为k的节点。
* @param k 节点的键值
* @return 返回键值为k的节点
*/
public Node search(int k) {
return search(root, k);
}
/**
* 采用递归法查找键值为k的节点。
* @param x 当前节点
* @param k 节点的键值
* @return 返回键值为k的节点
*/
private Node search(Node x, int k) {
if(x == nil || k == x.key) {
return x;
} else if(k < x.key) {
return search(x.left, k);
} else {
return search(x.right, k);
}
}
/**
* 采用迭代法查找键值为k的节点。
* @param x 当前节点
* @param k 节点的键值
* @return 返回键值为k的节点
*/
public Node iterativeSearch(int k) {
return iterativeSearch(root, k);
}
/**
* 采用迭代法查找键值为k的节点。
* @param x 当前节点
* @param k 节点的键值
* @return 返回键值为k的节点
*/
private Node iterativeSearch(Node x, int k) {
while(x != nil && k != x.key) {
if(k < x.key) {
x = x.left;
} else {
x = x.right;
}
}
return x;
}
/**
* 返回树的最小键值的节点。
* @return 最小键值的节点
*/
public Node minimum() {
return minimum(root);
}
/**
* 返回树的最小键值的节点。
* @param x 当前节点
* @return 最小键值的节点
*/
private Node minimum(Node x) {
while(x.left != nil) {
x = x.left;
}
return x;
}
/**
* 返回树的最大键值的节点。
* @return 最大键值的节点
*/
public Node maximum() {
return maximum(root);
}
/**
* 返回树的最大键值的节点。
* @param x 当前节点
* @return 最大键值的节点
*/
private Node maximum(Node x) {
while(x.right != nil) {
x = x.right;
}
return x;
}
/**
* 返回指定节点x的后继节点。
* @param x 当前节点
* @return x的后继节点;如果x具有最大键值,返回null
*/
public Node successor(Node x) {
if(x.right != nil) {
return minimum(x.right);
}
Node y = x.parent;
while(y != nil && x == y.right) {
x = y;
y = y.parent;
}
return y;
}
/**
* 返回指定节点x的前驱节点。
* @param x 当前节点
* @return x的前驱节点;如果x具有最小键值,返回null
*/
public Node predecessor(Node x) {
if(x.left != nil) {
return maximum(x.left);
}
Node y = x.parent;
while(y != nil && x == y.left) {
x = y;
y = y.parent;
}
return y;
}
/**
* 插入节点。
* @param z 待插入节点
*/
public void insert(Node z) {
Node y = nil; //当前节点的父节点
Node x = root; //当前节点
while(x != nil) { //迭代查寻z应该所在的位置
y = x;
if(z.key < x.key) {
x = x.left;
} else {
x = x.right;
}
}
z.parent = y;
if(y == nil) {
root = z; //如果没有父节点,则插入的节点是根节点。
} else if(z.key < y.key) {
y.left = z;
} else {
y.right = z;
}
z.left = nil;
z.right = nil;
z.color = Color.RED;
insertFixup(z);
}
/**
* 按红黑树规则进行调整。
* @param z 待插入节点
*/
public void insertFixup(Node z) {
while(z.parent.color == Color.RED) { //违反条件4,并且保证z有爷爷
if(z.parent == z.parent.parent.left) { //z的父节点是左子节点
Node y = z.parent.parent.right;
if(y.color == Color.RED) { //如果z的叔叔是红
z.parent.color = Color.BLACK; //将z的父亲和叔叔设为黑
y.color = Color.BLACK;
z.parent.parent.color = Color.RED; //z的爷爷设为红
z = z.parent.parent; //迭代
} else { //如果z的叔叔是黑
if (z == z.parent.right) { //如果z是右子节点,左旋
z = z.parent;
leftRotate(z);
}
z.parent.color = Color.BLACK; //z的父亲为黑(叔叔为黑)
z.parent.parent.color = Color.RED; //z的爷爷为红
rightRotate(z.parent.parent); // 右旋
}
} else { //z的父节点是右子节点,反向对称
Node y = z.parent.parent.left;
if(y.color == Color.RED) {
z.parent.color = Color.BLACK;
y.color = Color.BLACK;
z.parent.parent.color = Color.RED;
z = z.parent.parent;
} else {
if (z == z.parent.left) {
z = z.parent;
rightRotate(z);
}
z.parent.color = Color.BLACK;
z.parent.parent.color = Color.RED;
leftRotate(z.parent.parent);
}
}
}
root.color = Color.BLACK; //满足条件2
}
/**
* 删除节点。
* @param z 待删除节点
*/
public Node delete(Node z) {
Node y = null;
Node x = null;
if (z.left == nil || z.right == nil) {
y = z;
} else {
y = successor(z);
}
if (y.left != nil) {
x = y.left;
} else {
x = y.right;
}
x.parent = y.parent;
if (y.parent == nil) {
root = x;
} else if (y == y.parent.left) {
y.parent.left = x;
} else {
y.parent.right = x;
}
if (y != z) { //如果z包含两个子节点,用y替换z的位置
z.key = y.key;
}
if(y.color == Color.BLACK) {
deleteFixup(x);
}
return y;
}
/**
* 按红黑树规则进行调整。
* @param z 待删除节点
*/
private void deleteFixup(Node x) {
while(x != root && x.color == Color.BLACK) {
if(x == x.parent.left) {
Node w = x.parent.right;
if(w.color == Color.RED) {
w.color = Color.BLACK;
x.parent.color = Color.RED;
leftRotate(x.parent);
w = x.parent.right;
}
if(w.left.color == Color.BLACK && w.right.color == Color.BLACK) {
w.color = Color.RED;
x = x.parent;
} else {
if(w.right.color == Color.BLACK) {
w.left.color = Color.BLACK;
w.color = Color.RED;
rightRotate(w);
w = x.parent.right;
}
w.color = x.parent.color;
x.parent.color = Color.BLACK;
w.right.color = Color.BLACK;
leftRotate(x.parent);
x = root;
}
} else {
Node w = x.parent.left;
if(w.color == Color.RED) {
w.color = Color.BLACK;
x.parent.color = Color.RED;
rightRotate(x.parent);
w = x.parent.left;
}
if(w.right.color == Color.BLACK && w.left.color == Color.BLACK) {
w.color = Color.RED;
x = x.parent;
} else {
if(w.left.color == Color.BLACK) {
w.right.color = Color.BLACK;
w.color = Color.RED;
leftRotate(w);
w = x.parent.left;
//preorderWalk();
}
w.color = x.parent.color;
x.parent.color = Color.BLACK;
w.left.color = Color.BLACK;
rightRotate(x.parent);
x = root;
}
}
}
x.color = Color.BLACK;
}
/**
* 中序遍历。即从小到大排序。
* @return 返回已排序的节点列表
*/
public List<Node> inorderWalk() {
List<Node> list = new ArrayList<Node>();
inorderWalk(root, list);
return list;
}
/**
* 中序遍历。
* @param x 当前节点
* @param list 遍历结果存储在list中
*/
private void inorderWalk(Node x, List<Node> list) {
if(x != nil) {
inorderWalk(x.left, list);
list.add(x);
inorderWalk(x.right, list);
}
}
/**
* 前序遍历打印。即从小到大排序。
* @return 返回已排序的节点列表
*/
public void preorderWalk() {
preorderWalk(root);
}
/**
* 中序遍历打印。
* @param x 当前节点
* @param list 遍历结果存储在list中
*/
private void preorderWalk(Node x) {
if(x != nil) {
System.out.print("(");
System.out.print(x);
preorderWalk(x.left);
preorderWalk(x.right);
System.out.print(")");
} else {
System.out.print("N");
}
}
}
import java.util.List;
import junit.framework.TestCase;
public class RedBlackTreeTest extends TestCase {
public void testLinkedList() {
RedBlackTree tree = new RedBlackTree();
// 插入N个随机节点
int count = 100;
for (int i = 0; i < count;) {
int key = (int) (Math.random() * 100);
if (tree.search(key) == tree.nil) {
tree.insert(new RedBlackTree.Node(key));
i++;
}
}
//测试最大值,最小值
List<RedBlackTree.Node> list = tree.inorderWalk();
verifyOrdered(list);
assertEquals(count, list.size());
assertEquals(list.get(0), tree.minimum());
assertEquals(list.get(list.size() - 1), tree.maximum());
//测试后继
RedBlackTree.Node min = tree.minimum(), succ = null;
while((succ=tree.successor(min)) != tree.nil) {
assertTrue(succ.key > min.key);
min = succ;
}
//测试前驱
RedBlackTree.Node max = tree.maximum(), pre = null;
while((pre=tree.predecessor(max)) != tree.nil) {
assertTrue(succ.key < max.key);
max = pre;
}
//测试删除
int[] keys = new int[list.size()];
for(int i = 0; i < keys.length; i++) {
keys[i] = list.get(i).key;
}
PermuteBySorting.permute(keys);
for (int i = 0; i < count; i++) {
RedBlackTree.Node node = tree.search(keys[i]);
assertNotNull(node);
tree.delete(node);
assertEquals(tree.nil, tree.search(keys[i]));
verifyOrdered(tree.inorderWalk());
}
}
private boolean verifyOrdered(List<RedBlackTree.Node> list) {
for (int i = 1; i < list.size(); i++) {
if (list.get(i - 1).key > list.get(i).key) {
return false;
}
}
return true;
}
}
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
/*-----------------------------------------------------------
RB-Tree的插入和删除操作的实现算法
参考资料:
1) <<Introduction to algorithm>>
2) <<STL源码剖析>>
3) sgi-stl中stl_tree.h中的实现算法
4) http://epaperpress.com/sortsearch/index.html
5) http://www.ececs.uc.edu/~franco/C321/html/RedBlack/redblack.html
作者:李创 ( http://www.cppblog.com/converse/ )
您可以自由的传播,修改这份代码,转载处请注明原作者
红黑树的几个性质:
1) 每个结点只有红和黑两种颜色
2) 根结点是黑色的
3) 每个叶子结点(空结点被认为是叶子结点)是黑色的
4) 如果一个结点是红色的,那么它的左右两个子结点的颜色是黑色的
5) 对于每个结点而言,从这个结点到叶子结点的任何路径上的黑色结点
的数目相同
-------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef int KEY;
enum NODECOLOR
{
BLACK = 0,
RED = 1
};
typedef struct RBTree
{
struct RBTree *parent;
struct RBTree *left, *right;
KEY key;
NODECOLOR color;
}RBTree, *PRBTree;
PRBTree RB_InsertNode(PRBTree root, KEY key);
PRBTree RB_InsertNode_Fixup(PRBTree root, PRBTree z);
PRBTree RB_DeleteNode(PRBTree root, KEY key);
PRBTree RB_DeleteNode_Fixup(PRBTree root, PRBTree z);
PRBTree Find_Node(PRBTree root, KEY key);
void Left_Rotate(PRBTree A, PRBTree& root);
void Right_Rotate(PRBTree A, PRBTree& root);
void Mid_Visit(PRBTree T);
void Mid_DeleteTree(PRBTree T);
void Print_Node(PRBTree node);
/*-----------------------------------------------------------
| A B
| / / ==> / /
| a B A y
| / / / /
| b y a b
-----------------------------------------------------------*/
void Left_Rotate(PRBTree A, PRBTree& root)
{
PRBTree B;
B = A->right;
if (NULL == B)
return;
A->right = B->left;
if (NULL != B->left)
B->left->parent = A;
B->parent = A->parent;
// 这样三个判断连在一起避免了A->parent = NULL的情况
if (A == root)
{
root = B;
}
else if (A == A->parent->left)
{
A->parent->left = B;
}
else
{
A->parent->right = B;
}
B->left = A;
A->parent = B;
}
/*-----------------------------------------------------------
| A B
| / / / /
| B y ==> a A
| / / / /
|a b b y
-----------------------------------------------------------*/
void Right_Rotate(PRBTree A, PRBTree& root)
{
PRBTree B;
B = A->left;
if (NULL == B)
return;
A->left = B->right;
if (NULL != B->right)
B->right->parent = A;
B->parent = A->parent;
// 这样三个判断连在一起避免了A->parent = NULL的情况
if (A == root)
{
root = B;
}
else if (A == A->parent->left)
{
A->parent->left = B;
}
else
{
A->parent->right = B;
}
A->parent = B;
B->right = A;
}
/*-----------------------------------------------------------
| 函数作用:查找key值对应的结点指针
| 输入参数:根节点root,待查找关键值key
| 返回参数:如果找到返回结点指针,否则返回NULL
-------------------------------------------------------------*/
PRBTree Find_Node(PRBTree root, KEY key)
{
PRBTree x;
// 找到key所在的node
x = root;
do
{
if (key == x->key)
break;
if (key < x->key)
{
if (NULL != x->left)
x = x->left;
else
break;
}
else
{
if (NULL != x->right)
x = x->right;
else
break;
}
} while (NULL != x);
return x;
}
/*-----------------------------------------------------------
| 函数作用:在树中插入key值
| 输入参数:根节点root,待插入结点的关键值key
| 返回参数:根节点root
-------------------------------------------------------------*/
PRBTree RB_InsertNode(PRBTree root, KEY key)
{
PRBTree x, y;
PRBTree z;
if (NULL == (z = (PRBTree)malloc(sizeof(RBTree))))
{
printf("Memory alloc error/n");
return NULL;
}
z->key = key;
// 得到z的父节点
x = root, y = NULL;
while (NULL != x)
{
y = x;
if (z->key < x->key)
{
if (NULL != x->left)
{
x = x->left;
}
else
{
break;
}
}
else
{
if (NULL != x->right)
{
x = x->right;
}
else
{
break;
}
}
}
// 把z放到合适的位置
z->parent = y;
if (NULL == y)
{
root = z;
}
else
{
if (z->key < y->key)
y->left = z;
else
y->right = z;
}
// 设置z的左右子树为空并且颜色是red,注意新插入的节点颜色都是red
z->left = z->right = NULL;
z->color = RED;
// 对红黑树进行修正
return RB_InsertNode_Fixup(root, z);
}
/*-----------------------------------------------------------
| 函数作用:对插入key值之后的树进行修正
| 输入参数:根节点root,插入的结点z
| 返回参数:根节点root
-------------------------------------------------------------*/
PRBTree RB_InsertNode_Fixup(PRBTree root, PRBTree z)
{
PRBTree y;
while (root != z && RED == z->parent->color) // 当z不是根同时父节点的颜色是red
{
if (z->parent == z->parent->parent->left) // 父节点是祖父节点的左子树
{
y = z->parent->parent->right; // y为z的伯父节点
if (NULL != y && RED == y->color) // 伯父节点存在且颜色是red
{
z->parent->color = BLACK; // 更改z的父节点颜色是B
y->color = BLACK; // 更改z的伯父节点颜色是B
z->parent->parent->color = RED; // 更改z的祖父节点颜色是B
z = z->parent->parent; // 更新z为它的祖父节点
}
else // 无伯父节点或者伯父节点颜色是b
{
if (z == z->parent->right) // 如果新节点是父节点的右子树
{
z = z->parent;
Left_Rotate(z, root);
}
z->parent->color = BLACK; // 改变父节点颜色是B
z->parent->parent->color = RED; // 改变祖父节点颜色是R
Right_Rotate(z->parent->parent, root);
}
}
else // 父节点为祖父节点的右子树
{
y = z->parent->parent->left; // y为z的伯父节点
if (NULL != y && RED == y->color) // 如果y的颜色是red
{
z->parent->color = BLACK; // 更改父节点的颜色为B
y->color = BLACK; // 更改伯父节点的颜色是B
z->parent->parent->color = RED; // 更改祖父节点颜色是R
z = z->parent->parent; // 更改z指向祖父节点
}
else // y不存在或者颜色是B
{
if (z == z->parent->left) // 如果是父节点的左子树
{
z = z->parent;
Right_Rotate(z, root);
}
z->parent->color = BLACK; // 改变父节点的颜色是B
z->parent->parent->color = RED; // 改变祖父节点的颜色是RED
Left_Rotate(z->parent->parent, root);
}
}
} // while(RED == z->parent->color)
// 根节点的颜色始终都是B
root->color = BLACK;
return root;
}
/*-----------------------------------------------------------
| 函数作用:在树中删除key值
| 输入参数:根节点root,待插入结点的关键值key
| 返回参数:根节点root
-------------------------------------------------------------*/
PRBTree RB_DeleteNode(PRBTree root, KEY key)
{
PRBTree x, y, z, x_parent;
z = Find_Node(root, key);
if (NULL == z)
return root;
// 当z有一个空子树的时候,y == z
// 否则,y是大于z最小的结点
if (NULL == z->left || NULL == z->right)
y = z;
else
{
y = z->right;
while (NULL != y->left)
y = y->left;
}
// x是y的子树,可能为NULL
if (NULL != y->left)
x = y->left;
else
x = y->right;
// 设定x的位置取代y
if (NULL != x)
x->parent = y->parent;
if (NULL == y->parent)
root = x;
else if (y == y->parent->left)
y->parent->left = x;
else
y->parent->right = x;
// 把y的key拷贝到z中,这样y就是待删除的结点了
if (y != z)
{
z->key = y->key;
}
// 如果y的颜色值是B,那么要对树进行修正
if (BLACK == y->color && NULL != x)
RB_DeleteNode_Fixup(root, x);
free(y);
return root;
}
/*-----------------------------------------------------------
| 函数作用:对删除key值之后的树进行修正
| 输入参数:根节点root,删除的结点的子结点x
| 返回参数:根节点root
-------------------------------------------------------------*/
PRBTree RB_DeleteNode_Fixup(PRBTree root, PRBTree x)
{
PRBTree w;
while (x != root && BLACK == x->color)
{
if (x == x->parent->left) // 如果x是左子树
{
w = x->parent->right; // w是x的兄弟结点
if (NULL == w)
continue;
if (RED == w->color) // 如果w的颜色是红色
{
w->color = BLACK;
x->parent->color = RED;
Left_Rotate(x->parent, root);
w = x->parent->right;
}
if (NULL != w->left && BLACK == w->left->color &&
NULL != w->right && BLACK == w->right->color)
{
w->color = RED;
x = x->parent;
}
else
{
if (NULL != w->right && BLACK == w->right->color)
{
w->left->color = BLACK;
w->color = RED;
Right_Rotate(w, root);
w = x->parent->right;
}
w->color = x->parent->color;
x->parent->color = BLACK;
w->right->color = BLACK;
Left_Rotate(x->parent, root);
x = root;
}
}
else
{
w = x->parent->left;
if (NULL == w)
continue;
if (RED == w->color)
{
w->color = BLACK;
x->parent->color = RED;
Left_Rotate(x->parent, root);
w = x->parent->left;
}
if (NULL != w->left && BLACK == w->left->color &&
NULL != w->right && BLACK == w->right->color)
{
w->color = RED;
x = x->parent;
}
else
{
if (NULL != w->left && BLACK == w->left->color)
{
w->right->color = BLACK;
w->color = RED;
Left_Rotate(w, root);
w = x->parent->left;
}
w->color = x->parent->color;
x->parent->color = BLACK;
w->left->color = BLACK;
Right_Rotate(x->parent, root);
x = root;
}
}
}
x->color = BLACK;
return root;
}
void Print_Node(PRBTree node)
{
char* color[] = {"BLACK", "RED"};
printf("Key = %d,/tcolor = %s", node->key, color[node->color]);
if (NULL != node->parent)
printf(",/tparent = %d", node->parent->key);
if (NULL != node->left)
printf(",/tleft = %d", node->left->key);
if (NULL != node->right)
printf(",/tright = %d", node->right->key);
printf("/n");
}
// 中序遍历树
void Mid_Visit(PRBTree T)
{
if (NULL != T)
{
if (NULL != T->left)
Mid_Visit(T->left);
Print_Node(T);
if (NULL != T->right)
Mid_Visit(T->right);
}
}
// 中序删除树的各个节点
void Mid_DeleteTree(PRBTree T)
{
if (NULL != T)
{
if (NULL != T->left)
Mid_DeleteTree(T->left);
PRBTree temp = T->right;
free(T);
T = NULL;
if (NULL != temp)
Mid_DeleteTree(temp);
}
}
void Create_New_Array(int array[], int length)
{
for (int i = 0; i < length; i++)
{
array[i] = rand() % 256;
}
}
int main(int argc, char *argv[])
{
//int array[10] = {80, 116, 81, 205, 82, 68, 151, 20, 109, 100};
int array[10];
srand(time(NULL));
Create_New_Array(array, 10);
PRBTree root = NULL;
int i;
for (i = 0; i < 10; i++)
{
root = RB_InsertNode(root, array[i]);
}
Mid_Visit(root);
// 随机删除一个结点
int index = rand() % 10;
printf("delete node %d/n", array[index]);
root = RB_DeleteNode(root, array[index]);
Mid_Visit(root);
// 删除整颗树
Mid_DeleteTree(root);
return 0;
}
**
* Introduction to Algorithms, Second Edition
* 13 Red-Black Trees
*
* 红黑树的条件:
* 1.每个节点标记为“红”或“黑”。
* 2.根标记为“黑”。
* 3.所有叶节点(nil)标记为“黑”。
* 4.如果一个节点为“红”,则它的两个节点都为“黑”。
* 5.对每个的节点,从该节点至后继叶节点包含相同数量的“黑”节点。
* @author 土豆爸爸
*
*/
import java.util.ArrayList;
import java.util.List;
public class RedBlackTree {
/**
* 数据节点
*/
public static class Node {
int key;
Node parent; //父节点
Node left; //左子节点
Node right; //右子节点
Color color; //节点颜色
public Node(int key) {
this.key = key;
}
public String toString() {
return String.valueOf(key);
}
}
/**
* 颜色
*/
private enum Color { RED, BLACK};
Node root; //根节点
Node nil; //空节点
/**
* 构造函数
*/
public RedBlackTree() {
nil = new Node(-1);
nil.color = Color.BLACK;
root = nil;
}
/**
* 左旋转。
* @param x 支点
*/
private void leftRotate(Node x) {
Node y = x.right; // y是x的右子节点
x.right = y.left; // y的左子树转换成x的右子树
if (y.left != nil)
y.left.parent = x;
y.parent = x.parent; // 用y替换x的位置
if (x.parent == nil) {
root = y;
} else if (x == x.parent.left) {
x.parent.left = y;
} else {
x.parent.right = y;
}
y.left = x; // 将x设置为y的左子节点
x.parent = y;
}
/**
* 右旋转。
* @param x 支点
*/
private void rightRotate(Node y) {
Node x = y.left; // y是x的右子节点
y.left = x.right; // y的左子树转换成x的右子树
if (x.right != nil)
x.right.parent = y;
x.parent = y.parent; // 用y替换x的位置
if (y.parent == nil) {
root = x;
} else if (y == y.parent.left) {
y.parent.left = x;
} else {
y.parent.right = x;
}
x.right = y; // 将x设置为y的左子节点
y.parent = x;
}
/**
* 采用递归法查找键值为k的节点。
* @param k 节点的键值
* @return 返回键值为k的节点
*/
public Node search(int k) {
return search(root, k);
}
/**
* 采用递归法查找键值为k的节点。
* @param x 当前节点
* @param k 节点的键值
* @return 返回键值为k的节点
*/
private Node search(Node x, int k) {
if(x == nil || k == x.key) {
return x;
} else if(k < x.key) {
return search(x.left, k);
} else {
return search(x.right, k);
}
}
/**
* 采用迭代法查找键值为k的节点。
* @param x 当前节点
* @param k 节点的键值
* @return 返回键值为k的节点
*/
public Node iterativeSearch(int k) {
return iterativeSearch(root, k);
}
/**
* 采用迭代法查找键值为k的节点。
* @param x 当前节点
* @param k 节点的键值
* @return 返回键值为k的节点
*/
private Node iterativeSearch(Node x, int k) {
while(x != nil && k != x.key) {
if(k < x.key) {
x = x.left;
} else {
x = x.right;
}
}
return x;
}
/**
* 返回树的最小键值的节点。
* @return 最小键值的节点
*/
public Node minimum() {
return minimum(root);
}
/**
* 返回树的最小键值的节点。
* @param x 当前节点
* @return 最小键值的节点
*/
private Node minimum(Node x) {
while(x.left != nil) {
x = x.left;
}
return x;
}
/**
* 返回树的最大键值的节点。
* @return 最大键值的节点
*/
public Node maximum() {
return maximum(root);
}
/**
* 返回树的最大键值的节点。
* @param x 当前节点
* @return 最大键值的节点
*/
private Node maximum(Node x) {
while(x.right != nil) {
x = x.right;
}
return x;
}
/**
* 返回指定节点x的后继节点。
* @param x 当前节点
* @return x的后继节点;如果x具有最大键值,返回null
*/
public Node successor(Node x) {
if(x.right != nil) {
return minimum(x.right);
}
Node y = x.parent;
while(y != nil && x == y.right) {
x = y;
y = y.parent;
}
return y;
}
/**
* 返回指定节点x的前驱节点。
* @param x 当前节点
* @return x的前驱节点;如果x具有最小键值,返回null
*/
public Node predecessor(Node x) {
if(x.left != nil) {
return maximum(x.left);
}
Node y = x.parent;
while(y != nil && x == y.left) {
x = y;
y = y.parent;
}
return y;
}
/**
* 插入节点。
* @param z 待插入节点
*/
public void insert(Node z) {
Node y = nil; //当前节点的父节点
Node x = root; //当前节点
while(x != nil) { //迭代查寻z应该所在的位置
y = x;
if(z.key < x.key) {
x = x.left;
} else {
x = x.right;
}
}
z.parent = y;
if(y == nil) {
root = z; //如果没有父节点,则插入的节点是根节点。
} else if(z.key < y.key) {
y.left = z;
} else {
y.right = z;
}
z.left = nil;
z.right = nil;
z.color = Color.RED;
insertFixup(z);
}
/**
* 按红黑树规则进行调整。
* @param z 待插入节点
*/
public void insertFixup(Node z) {
while(z.parent.color == Color.RED) { //违反条件4,并且保证z有爷爷
if(z.parent == z.parent.parent.left) { //z的父节点是左子节点
Node y = z.parent.parent.right;
if(y.color == Color.RED) { //如果z的叔叔是红
z.parent.color = Color.BLACK; //将z的父亲和叔叔设为黑
y.color = Color.BLACK;
z.parent.parent.color = Color.RED; //z的爷爷设为红
z = z.parent.parent; //迭代
} else { //如果z的叔叔是黑
if (z == z.parent.right) { //如果z是右子节点,左旋
z = z.parent;
leftRotate(z);
}
z.parent.color = Color.BLACK; //z的父亲为黑(叔叔为黑)
z.parent.parent.color = Color.RED; //z的爷爷为红
rightRotate(z.parent.parent); // 右旋
}
} else { //z的父节点是右子节点,反向对称
Node y = z.parent.parent.left;
if(y.color == Color.RED) {
z.parent.color = Color.BLACK;
y.color = Color.BLACK;
z.parent.parent.color = Color.RED;
z = z.parent.parent;
} else {
if (z == z.parent.left) {
z = z.parent;
rightRotate(z);
}
z.parent.color = Color.BLACK;
z.parent.parent.color = Color.RED;
leftRotate(z.parent.parent);
}
}
}
root.color = Color.BLACK; //满足条件2
}
/**
* 删除节点。
* @param z 待删除节点
*/
public Node delete(Node z) {
Node y = null;
Node x = null;
if (z.left == nil || z.right == nil) {
y = z;
} else {
y = successor(z);
}
if (y.left != nil) {
x = y.left;
} else {
x = y.right;
}
x.parent = y.parent;
if (y.parent == nil) {
root = x;
} else if (y == y.parent.left) {
y.parent.left = x;
} else {
y.parent.right = x;
}
if (y != z) { //如果z包含两个子节点,用y替换z的位置
z.key = y.key;
}
if(y.color == Color.BLACK) {
deleteFixup(x);
}
return y;
}
/**
* 按红黑树规则进行调整。
* @param z 待删除节点
*/
private void deleteFixup(Node x) {
while(x != root && x.color == Color.BLACK) {
if(x == x.parent.left) {
Node w = x.parent.right;
if(w.color == Color.RED) {
w.color = Color.BLACK;
x.parent.color = Color.RED;
leftRotate(x.parent);
w = x.parent.right;
}
if(w.left.color == Color.BLACK && w.right.color == Color.BLACK) {
w.color = Color.RED;
x = x.parent;
} else {
if(w.right.color == Color.BLACK) {
w.left.color = Color.BLACK;
w.color = Color.RED;
rightRotate(w);
w = x.parent.right;
}
w.color = x.parent.color;
x.parent.color = Color.BLACK;
w.right.color = Color.BLACK;
leftRotate(x.parent);
x = root;
}
} else {
Node w = x.parent.left;
if(w.color == Color.RED) {
w.color = Color.BLACK;
x.parent.color = Color.RED;
rightRotate(x.parent);
w = x.parent.left;
}
if(w.right.color == Color.BLACK && w.left.color == Color.BLACK) {
w.color = Color.RED;
x = x.parent;
} else {
if(w.left.color == Color.BLACK) {
w.right.color = Color.BLACK;
w.color = Color.RED;
leftRotate(w);
w = x.parent.left;
//preorderWalk();
}
w.color = x.parent.color;
x.parent.color = Color.BLACK;
w.left.color = Color.BLACK;
rightRotate(x.parent);
x = root;
}
}
}
x.color = Color.BLACK;
}
/**
* 中序遍历。即从小到大排序。
* @return 返回已排序的节点列表
*/
public List<Node> inorderWalk() {
List<Node> list = new ArrayList<Node>();
inorderWalk(root, list);
return list;
}
/**
* 中序遍历。
* @param x 当前节点
* @param list 遍历结果存储在list中
*/
private void inorderWalk(Node x, List<Node> list) {
if(x != nil) {
inorderWalk(x.left, list);
list.add(x);
inorderWalk(x.right, list);
}
}
/**
* 前序遍历打印。即从小到大排序。
* @return 返回已排序的节点列表
*/
public void preorderWalk() {
preorderWalk(root);
}
/**
* 中序遍历打印。
* @param x 当前节点
* @param list 遍历结果存储在list中
*/
private void preorderWalk(Node x) {
if(x != nil) {
System.out.print("(");
System.out.print(x);
preorderWalk(x.left);
preorderWalk(x.right);
System.out.print(")");
} else {
System.out.print("N");
}
}
}
import java.util.List;
import junit.framework.TestCase;
public class RedBlackTreeTest extends TestCase {
public void testLinkedList() {
RedBlackTree tree = new RedBlackTree();
// 插入N个随机节点
int count = 100;
for (int i = 0; i < count;) {
int key = (int) (Math.random() * 100);
if (tree.search(key) == tree.nil) {
tree.insert(new RedBlackTree.Node(key));
i++;
}
}
//测试最大值,最小值
List<RedBlackTree.Node> list = tree.inorderWalk();
verifyOrdered(list);
assertEquals(count, list.size());
assertEquals(list.get(0), tree.minimum());
assertEquals(list.get(list.size() - 1), tree.maximum());
//测试后继
RedBlackTree.Node min = tree.minimum(), succ = null;
while((succ=tree.successor(min)) != tree.nil) {
assertTrue(succ.key > min.key);
min = succ;
}
//测试前驱
RedBlackTree.Node max = tree.maximum(), pre = null;
while((pre=tree.predecessor(max)) != tree.nil) {
assertTrue(succ.key < max.key);
max = pre;
}
//测试删除
int[] keys = new int[list.size()];
for(int i = 0; i < keys.length; i++) {
keys[i] = list.get(i).key;
}
PermuteBySorting.permute(keys);
for (int i = 0; i < count; i++) {
RedBlackTree.Node node = tree.search(keys[i]);
assertNotNull(node);
tree.delete(node);
assertEquals(tree.nil, tree.search(keys[i]));
verifyOrdered(tree.inorderWalk());
}
}
private boolean verifyOrdered(List<RedBlackTree.Node> list) {
for (int i = 1; i < list.size(); i++) {
if (list.get(i - 1).key > list.get(i).key) {
return false;
}
}
return true;
}
}
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
/*-----------------------------------------------------------
RB-Tree的插入和删除操作的实现算法
参考资料:
1) <<Introduction to algorithm>>
2) <<STL源码剖析>>
3) sgi-stl中stl_tree.h中的实现算法
4) http://epaperpress.com/sortsearch/index.html
5) http://www.ececs.uc.edu/~franco/C321/html/RedBlack/redblack.html
作者:李创 ( http://www.cppblog.com/converse/ )
您可以自由的传播,修改这份代码,转载处请注明原作者
红黑树的几个性质:
1) 每个结点只有红和黑两种颜色
2) 根结点是黑色的
3) 每个叶子结点(空结点被认为是叶子结点)是黑色的
4) 如果一个结点是红色的,那么它的左右两个子结点的颜色是黑色的
5) 对于每个结点而言,从这个结点到叶子结点的任何路径上的黑色结点
的数目相同
-------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef int KEY;
enum NODECOLOR
{
BLACK = 0,
RED = 1
};
typedef struct RBTree
{
struct RBTree *parent;
struct RBTree *left, *right;
KEY key;
NODECOLOR color;
}RBTree, *PRBTree;
PRBTree RB_InsertNode(PRBTree root, KEY key);
PRBTree RB_InsertNode_Fixup(PRBTree root, PRBTree z);
PRBTree RB_DeleteNode(PRBTree root, KEY key);
PRBTree RB_DeleteNode_Fixup(PRBTree root, PRBTree z);
PRBTree Find_Node(PRBTree root, KEY key);
void Left_Rotate(PRBTree A, PRBTree& root);
void Right_Rotate(PRBTree A, PRBTree& root);
void Mid_Visit(PRBTree T);
void Mid_DeleteTree(PRBTree T);
void Print_Node(PRBTree node);
/*-----------------------------------------------------------
| A B
| / / ==> / /
| a B A y
| / / / /
| b y a b
-----------------------------------------------------------*/
void Left_Rotate(PRBTree A, PRBTree& root)
{
PRBTree B;
B = A->right;
if (NULL == B)
return;
A->right = B->left;
if (NULL != B->left)
B->left->parent = A;
B->parent = A->parent;
// 这样三个判断连在一起避免了A->parent = NULL的情况
if (A == root)
{
root = B;
}
else if (A == A->parent->left)
{
A->parent->left = B;
}
else
{
A->parent->right = B;
}
B->left = A;
A->parent = B;
}
/*-----------------------------------------------------------
| A B
| / / / /
| B y ==> a A
| / / / /
|a b b y
-----------------------------------------------------------*/
void Right_Rotate(PRBTree A, PRBTree& root)
{
PRBTree B;
B = A->left;
if (NULL == B)
return;
A->left = B->right;
if (NULL != B->right)
B->right->parent = A;
B->parent = A->parent;
// 这样三个判断连在一起避免了A->parent = NULL的情况
if (A == root)
{
root = B;
}
else if (A == A->parent->left)
{
A->parent->left = B;
}
else
{
A->parent->right = B;
}
A->parent = B;
B->right = A;
}
/*-----------------------------------------------------------
| 函数作用:查找key值对应的结点指针
| 输入参数:根节点root,待查找关键值key
| 返回参数:如果找到返回结点指针,否则返回NULL
-------------------------------------------------------------*/
PRBTree Find_Node(PRBTree root, KEY key)
{
PRBTree x;
// 找到key所在的node
x = root;
do
{
if (key == x->key)
break;
if (key < x->key)
{
if (NULL != x->left)
x = x->left;
else
break;
}
else
{
if (NULL != x->right)
x = x->right;
else
break;
}
} while (NULL != x);
return x;
}
/*-----------------------------------------------------------
| 函数作用:在树中插入key值
| 输入参数:根节点root,待插入结点的关键值key
| 返回参数:根节点root
-------------------------------------------------------------*/
PRBTree RB_InsertNode(PRBTree root, KEY key)
{
PRBTree x, y;
PRBTree z;
if (NULL == (z = (PRBTree)malloc(sizeof(RBTree))))
{
printf("Memory alloc error/n");
return NULL;
}
z->key = key;
// 得到z的父节点
x = root, y = NULL;
while (NULL != x)
{
y = x;
if (z->key < x->key)
{
if (NULL != x->left)
{
x = x->left;
}
else
{
break;
}
}
else
{
if (NULL != x->right)
{
x = x->right;
}
else
{
break;
}
}
}
// 把z放到合适的位置
z->parent = y;
if (NULL == y)
{
root = z;
}
else
{
if (z->key < y->key)
y->left = z;
else
y->right = z;
}
// 设置z的左右子树为空并且颜色是red,注意新插入的节点颜色都是red
z->left = z->right = NULL;
z->color = RED;
// 对红黑树进行修正
return RB_InsertNode_Fixup(root, z);
}
/*-----------------------------------------------------------
| 函数作用:对插入key值之后的树进行修正
| 输入参数:根节点root,插入的结点z
| 返回参数:根节点root
-------------------------------------------------------------*/
PRBTree RB_InsertNode_Fixup(PRBTree root, PRBTree z)
{
PRBTree y;
while (root != z && RED == z->parent->color) // 当z不是根同时父节点的颜色是red
{
if (z->parent == z->parent->parent->left) // 父节点是祖父节点的左子树
{
y = z->parent->parent->right; // y为z的伯父节点
if (NULL != y && RED == y->color) // 伯父节点存在且颜色是red
{
z->parent->color = BLACK; // 更改z的父节点颜色是B
y->color = BLACK; // 更改z的伯父节点颜色是B
z->parent->parent->color = RED; // 更改z的祖父节点颜色是B
z = z->parent->parent; // 更新z为它的祖父节点
}
else // 无伯父节点或者伯父节点颜色是b
{
if (z == z->parent->right) // 如果新节点是父节点的右子树
{
z = z->parent;
Left_Rotate(z, root);
}
z->parent->color = BLACK; // 改变父节点颜色是B
z->parent->parent->color = RED; // 改变祖父节点颜色是R
Right_Rotate(z->parent->parent, root);
}
}
else // 父节点为祖父节点的右子树
{
y = z->parent->parent->left; // y为z的伯父节点
if (NULL != y && RED == y->color) // 如果y的颜色是red
{
z->parent->color = BLACK; // 更改父节点的颜色为B
y->color = BLACK; // 更改伯父节点的颜色是B
z->parent->parent->color = RED; // 更改祖父节点颜色是R
z = z->parent->parent; // 更改z指向祖父节点
}
else // y不存在或者颜色是B
{
if (z == z->parent->left) // 如果是父节点的左子树
{
z = z->parent;
Right_Rotate(z, root);
}
z->parent->color = BLACK; // 改变父节点的颜色是B
z->parent->parent->color = RED; // 改变祖父节点的颜色是RED
Left_Rotate(z->parent->parent, root);
}
}
} // while(RED == z->parent->color)
// 根节点的颜色始终都是B
root->color = BLACK;
return root;
}
/*-----------------------------------------------------------
| 函数作用:在树中删除key值
| 输入参数:根节点root,待插入结点的关键值key
| 返回参数:根节点root
-------------------------------------------------------------*/
PRBTree RB_DeleteNode(PRBTree root, KEY key)
{
PRBTree x, y, z, x_parent;
z = Find_Node(root, key);
if (NULL == z)
return root;
// 当z有一个空子树的时候,y == z
// 否则,y是大于z最小的结点
if (NULL == z->left || NULL == z->right)
y = z;
else
{
y = z->right;
while (NULL != y->left)
y = y->left;
}
// x是y的子树,可能为NULL
if (NULL != y->left)
x = y->left;
else
x = y->right;
// 设定x的位置取代y
if (NULL != x)
x->parent = y->parent;
if (NULL == y->parent)
root = x;
else if (y == y->parent->left)
y->parent->left = x;
else
y->parent->right = x;
// 把y的key拷贝到z中,这样y就是待删除的结点了
if (y != z)
{
z->key = y->key;
}
// 如果y的颜色值是B,那么要对树进行修正
if (BLACK == y->color && NULL != x)
RB_DeleteNode_Fixup(root, x);
free(y);
return root;
}
/*-----------------------------------------------------------
| 函数作用:对删除key值之后的树进行修正
| 输入参数:根节点root,删除的结点的子结点x
| 返回参数:根节点root
-------------------------------------------------------------*/
PRBTree RB_DeleteNode_Fixup(PRBTree root, PRBTree x)
{
PRBTree w;
while (x != root && BLACK == x->color)
{
if (x == x->parent->left) // 如果x是左子树
{
w = x->parent->right; // w是x的兄弟结点
if (NULL == w)
continue;
if (RED == w->color) // 如果w的颜色是红色
{
w->color = BLACK;
x->parent->color = RED;
Left_Rotate(x->parent, root);
w = x->parent->right;
}
if (NULL != w->left && BLACK == w->left->color &&
NULL != w->right && BLACK == w->right->color)
{
w->color = RED;
x = x->parent;
}
else
{
if (NULL != w->right && BLACK == w->right->color)
{
w->left->color = BLACK;
w->color = RED;
Right_Rotate(w, root);
w = x->parent->right;
}
w->color = x->parent->color;
x->parent->color = BLACK;
w->right->color = BLACK;
Left_Rotate(x->parent, root);
x = root;
}
}
else
{
w = x->parent->left;
if (NULL == w)
continue;
if (RED == w->color)
{
w->color = BLACK;
x->parent->color = RED;
Left_Rotate(x->parent, root);
w = x->parent->left;
}
if (NULL != w->left && BLACK == w->left->color &&
NULL != w->right && BLACK == w->right->color)
{
w->color = RED;
x = x->parent;
}
else
{
if (NULL != w->left && BLACK == w->left->color)
{
w->right->color = BLACK;
w->color = RED;
Left_Rotate(w, root);
w = x->parent->left;
}
w->color = x->parent->color;
x->parent->color = BLACK;
w->left->color = BLACK;
Right_Rotate(x->parent, root);
x = root;
}
}
}
x->color = BLACK;
return root;
}
void Print_Node(PRBTree node)
{
char* color[] = {"BLACK", "RED"};
printf("Key = %d,/tcolor = %s", node->key, color[node->color]);
if (NULL != node->parent)
printf(",/tparent = %d", node->parent->key);
if (NULL != node->left)
printf(",/tleft = %d", node->left->key);
if (NULL != node->right)
printf(",/tright = %d", node->right->key);
printf("/n");
}
// 中序遍历树
void Mid_Visit(PRBTree T)
{
if (NULL != T)
{
if (NULL != T->left)
Mid_Visit(T->left);
Print_Node(T);
if (NULL != T->right)
Mid_Visit(T->right);
}
}
// 中序删除树的各个节点
void Mid_DeleteTree(PRBTree T)
{
if (NULL != T)
{
if (NULL != T->left)
Mid_DeleteTree(T->left);
PRBTree temp = T->right;
free(T);
T = NULL;
if (NULL != temp)
Mid_DeleteTree(temp);
}
}
void Create_New_Array(int array[], int length)
{
for (int i = 0; i < length; i++)
{
array[i] = rand() % 256;
}
}
int main(int argc, char *argv[])
{
//int array[10] = {80, 116, 81, 205, 82, 68, 151, 20, 109, 100};
int array[10];
srand(time(NULL));
Create_New_Array(array, 10);
PRBTree root = NULL;
int i;
for (i = 0; i < 10; i++)
{
root = RB_InsertNode(root, array[i]);
}
Mid_Visit(root);
// 随机删除一个结点
int index = rand() % 10;
printf("delete node %d/n", array[index]);
root = RB_DeleteNode(root, array[index]);
Mid_Visit(root);
// 删除整颗树
Mid_DeleteTree(root);
return 0;
}