红黑树
来源:互联网 发布:曼陀罗训练软件 编辑:程序博客网 时间:2024/05/03 15:46
红黑树的性质:
性质1. 节点是红色或黑色。
性质2. 根节点是黑色。
性质3 每个叶节点是黑色的。
性质4 每个红色节点的两个子节点都是黑色。(从每个叶子到根的所有路径上不能有两个连续的红色节点)
性质5. 从任一节点到其每个叶子的所有路径都包含相同数目的黑色节点。
在根据算法导论可以得出一些算法的c++实现:(部分程序)
#include<iostream>
using namespace std;
#include"RB_TREE.h"
class RB_Tree{
private :
TreeNode1 * root;
TreeNode1 * findPos(int val){
TreeNode1* t = root;
TreeNode1*pre = root;
while (t != nill){
if (t->value == val)return t;
pre = t;
if (t->value < val) t = t->right;
else t = t->left;
}
return pre;
}
void RB_left_rotate(TreeNode1* t){
TreeNode1* y = t->right;
t->right = y->left;
if (y->left != nill){
y->left->p = t;
}
y->p = t->p;
if (t->p == nill){
root = y;
}else if(t == t->p->left){
t->p->left = y;
}
else{
t->p->right = y;
}
y->left = t;
t->p = y;
}
void RB_right_rotate(TreeNode1* t){
TreeNode1* y = t->left;
t->left = y->right;
if (y->right != nill){
y->right->p = t;
}
y->p = t->p;
if (t->p == nill){
root = y;
}
else if (t == t->p->right){
t->p->right = y;
}
else{
t->p->left = y;
}
y->right = t;
t->p = y;
}