RBtree

终结B站没人能讲清楚红黑树的历史,不服等你来踢馆!-【码炫课堂收费课节选之-红黑树源码解析及手写红黑树】_哔哩哔哩_bilibili

B站的听课记录,并写下如下红黑树c++版本代码,该课程真的史诗级推荐!

/*RBtreeNode.h*****/
#pragma once
enum { RED = false, BLACK = true };
template
class RBtreeNode
{
public:
	// 红黑树的左右节点及父节点
	RBtreeNode* parent;
	RBtreeNode* left;
	RBtreeNode* right;
	bool color;
	// 创建key 和 value的值
	K key;
	V value;
	/*构造函数**/
	RBtreeNode();
	RBtreeNode(RBtreeNode* parent, RBtreeNode* left, RBtreeNode* right, K key, V value,bool color);
	RBtreeNode(K key,V value, RBtreeNode* parent);
	void setVlue(K key,V value);
};





/*RBtreeNode.cpp*****/
#include "RBtreeNode.h"
// 默认构造函数,里面没有内容
template
RBtreeNode::RBtreeNode()
{
	this->parent = nullptr;
	this->left = nullptr;
	this->right = nullptr;
	// 主要是根节点为黑色,因此默认构造函数为黑色
	this->color = BLACK; 
}
template
RBtreeNode::RBtreeNode(RBtreeNode* parent, RBtreeNode* left, RBtreeNode* 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
RBtreeNode::RBtreeNode(K key, V value, RBtreeNode* parent)
{
	this->key = key;
	this->value = value;
	this->parent = parent;
	this->color = BLACK;
}
template
void RBtreeNode::setVlue(K key, V value)
{
	this->key = key;
	this->value = value;
}







/*RBtree.h*****/
#pragma once
#include "RBtreeNode.h"
using namespace std;
template
class RBtree
{
private:
	RBtreeNode* root;
	RBtreeNode* rightof(RBtreeNode* p) { return p->right; }; //获取右子
	RBtreeNode* leftof(RBtreeNode* p) { return p->left; }; //获取左子
	RBtreeNode* parentof(RBtreeNode* p) { return p->parent; }//获取父亲
	// 默认空节点
	RBtreeNode* colorof(RBtreeNode* p) { return p == nullptr ? p->color = BLACK : p->color = RED; } // 颜色更改
	const RBtreeNode* getRoot() { return root; }
	void setRoot(RBtreeNode* temp) { root = temp; }
	void fixAfterput(RBtreeNode* p);
	void fixAfterdelete(RBtreeNode* p); // 删除之后再修改
	// 查找前继节点
	RBtreeNode* predecessor(RBtreeNode* p);
	RBtreeNode* successor(RBtreeNode* p);

public:
	/*公有接口**/
	void leftRotate(RBtreeNode* p);
	void rightRotate(RBtreeNode* p);
	void put(K key, V value);
	// 删除节点操作
	void deleteNode(RBtreeNode* p);
	
};














/*RBtree.cpp*******/
#include "RBtree.h"
/**
     * 围绕p左旋
     *       pf                    pf
     *      /                     /
     *     p                     pr(r)
     *    / \          ==>      / \
     *  pl  pr(r)              p   rr
     *     / \                / \
    

你可能感兴趣的:(侯捷老师STL,c++,蓝桥杯)