终结B站没人能讲清楚红黑树的历史,不服等你来踢馆!-【码炫课堂收费课节选之-红黑树源码解析及手写红黑树】_哔哩哔哩_bilibili
B站的听课记录,并写下如下红黑树c++版本代码,该课程真的史诗级推荐!
/*RBtreeNode.h*****/
#pragma once
enum { RED = false, BLACK = true };
template<class K,class V >
class RBtreeNode
{
public:
// 红黑树的左右节点及父节点
RBtreeNode<K, V>* parent;
RBtreeNode<K, V>* left;
RBtreeNode<K, V>* right;
bool color;
// 创建key 和 value的值
K key;
V value;
/*构造函数**/
RBtreeNode();
RBtreeNode(RBtreeNode<K,V>* parent, RBtreeNode<K, V>* left, RBtreeNode<K, V>* right, K key, V value,bool color);
RBtreeNode(K key,V value, RBtreeNode<K, V>* parent);
void setVlue(K key,V value);
};
/*RBtreeNode.cpp*****/
#include "RBtreeNode.h"
// 默认构造函数,里面没有内容
template<class K,class V>
RBtreeNode<K, V>::RBtreeNode()
{
this->parent = nullptr;
this->left = nullptr;
this->right = nullptr;
// 主要是根节点为黑色,因此默认构造函数为黑色
this->color = BLACK;
}
template<class K, class V>
RBtreeNode<K, V>::RBtreeNode(RBtreeNode<K, V>* parent, RBtreeNode<K, V>* left, RBtreeNode<K, V>* right, K key, V value,bool color)
{
this->parent = parent;
this->left = left;
this->right = right;
this->key = key;
this->value = value;
this->color = color;
}
template<class K, class V>
RBtreeNode<K, V>::RBtreeNode(K key, V value, RBtreeNode<K, V>* parent)
{
this->key = key;
this->value = value;
this->parent = parent;
this->color = BLACK;
}
template<class K, class V>
void RBtreeNode<K, V>::setVlue(K key, V value)
{
this->key = key;
this->value = value;
}
/*RBtree.h*****/
#pragma once
#include "RBtreeNode.h"
using namespace std;
template<class K,class V>
class RBtree
{
private:
RBtreeNode<K,V>* root;
RBtreeNode<K, V>* rightof(RBtreeNode<K, V>* p) { return p->right; }; //获取右子
RBtreeNode<K, V>* leftof(RBtreeNode<K, V>* p) { return p->left; }; //获取左子
RBtreeNode<K, V>* parentof(RBtreeNode<K, V>* p) { return p->parent; }//获取父亲
// 默认空节点
RBtreeNode<K, V>* colorof(RBtreeNode<K, V>* p) { return p == nullptr ? p->color = BLACK : p->color = RED; } // 颜色更改
const RBtreeNode<K, V>* getRoot() { return root; }
void setRoot(RBtreeNode<K, V>* temp) { root = temp; }
void fixAfterput(RBtreeNode<K, V>* p);
void fixAfterdelete(RBtreeNode<K, V>* p); // 删除之后再修改
// 查找前继节点
RBtreeNode<K, V>* predecessor(RBtreeNode<K, V>* p);
RBtreeNode<K, V>* successor(RBtreeNode<K, V>* p);
public:
/*公有接口**/
void leftRotate(RBtreeNode<K, V>* p);
void rightRotate(RBtreeNode<K, V>* p);
void put(K key, V value);
// 删除节点操作
void deleteNode(RBtreeNode<K, V>* p);
};
/*RBtree.cpp*******/
#include "RBtree.h"
/**
* 围绕p左旋
* pf pf
* / /
* p pr(r)
* / \ ==> / \
* pl pr(r) p rr
* / \ / \