红黑树代码
map和set底层是红黑树,下面是之前模拟实现红黑树的代码
博主在红黑树的模拟实现一文的代码
#pragma once
// 节点的颜色
enum Colour
{
BLACK,
RED
};
template<class K, class V>
struct RBTreeNode
{
RBTreeNode<K, V>* _left; // 左子节点
RBTreeNode<K, V>* _right; // 右子节点
RBTreeNode<K, V>* _parent; // 父节点
Colour _col; // 节点的颜色
pair<K, V> _kv; // 节点的值
RBTreeNode(const pair<K, V>& kv)
:_left(nullptr)
, _right(nullptr)
, _parent(nullptr)
, _col(RED)
, _kv(kv)
{}
};
template<class K, class V>
class RBTree
{
typedef RBTreeNode<K, V> Node;
public:
RBTree()
:_root(nullptr)
{}
bool Insert(const pair<K, V>& kv)
{
if (_root == nullptr)
{
_root = new Node(kv);
_root->_col = BLACK;
return true;
}
Node* parent = nullptr;
Node* cur = _root;
while (cur)
{
if (cur->_kv.first < kv.first)
{
parent = cur;
cur = cur->_right;
}
else if (cur->_kv.first>kv.first)
{
parent = cur;
cur = cur->_left;
}
else
{
return false;
}
}
cur = new Node(kv);
cur->_col = RED;
if (parent->_kv.first < kv.first)
{
parent->_right = cur;
cur->_parent = parent;
}
else
{
parent->_left = cur;
cur->_parent = parent;
}
// 控制近似平衡
while (parent&&parent->_col == RED)
{
Node* grandparent = parent->_parent;
if (parent == grandparent->_left)
{
Node* uncle = grandparent->_right;
// 情况一:uncle存在且为红,进行变色处理,并继续往上更新处理
if (uncle&&uncle->_col == RED)
{
uncle->_col = BLACK;
parent->_col = BLACK;
grandparent->_col = RED;
cur = grandparent;
parent = cur->_parent;
}// 情况二+三:uncle不存在,或者存在且为黑,需要旋转+变色处理
else
{
// 情况二:单旋+变色
if (cur == parent->_left)
{
RotateR(grandparent);
parent->_col = BLACK;
grandparent->_col = RED;
}
else// 情况三:双旋 + 变色
{
RotateL(parent);
RotateR(grandparent);
cur->_col = BLACK;
grandparent->_col = RED;
}
break;
}
}
else // (parent == grandfather->_right)
{
Node* uncle = grandparent->_left;
if (uncle&&uncle->_col == RED)
{
uncle->_col = BLACK;
parent->_col = BLACK;
grandparent->_col = RED;
cur = grandparent;
parent = cur->_parent;
}
else
{
if (parent->_right == cur)
{
RotateL(grandparent);
parent->_col = BLACK;
grandparent->_col = RED;
}
else
{
RotateR(parent);
RotateL(grandparent);
cur->_col = BLACK;
grandparent->_col = RED;
}
break;
}
}
}
_root->_col = BLACK;
return true;
}
void RotateR(Node* parent)
{
Node* subL = parent->_left;
Node* subLR = subL->_right;
parent->_left = subLR;
if (subLR)
subLR->_parent = parent;
Node* ppNode = parent->_parent;
subL->_right = parent;
parent->_parent = subL;
if (parent == _root)
{
_root = subL;
subL->_parent = nullptr;
}
else
{
if (ppNode->_left == parent)
ppNode->_left = subL;
else
ppNode->_right = subL;
subL->_parent = ppNode;
}
}
void RotateL(Node* parent)
{
Node* subR = parent->_right;
Node* subRL = subR->_left;
parent->_right = subRL;
if (subRL)
subRL->_parent = parent;
Node* ppNode = parent->_parent;
subR->_left = parent;
parent->_parent = subR;
if (parent == _root)
{
_root = subR;
subR->_parent = nullptr;
}
else
{
if (ppNode->_left == parent)
{
ppNode->_left = subR;
}
else
{
ppNode->_right = subR;
}
subR->_parent = ppNode;
}
}
// 中序遍历输出节点
void _InOrder(Node* root)
{
if (root == nullptr)
{
return;
}
_InOrder(root->_left);
cout << root->_kv.first<<" ";
_InOrder(root->_right);
}
void InOrder()
{
_InOrder(_root);
cout << endl;
}
// 检测是否存在连续的红色节点
bool CheckRED_RED(Node* cur)
{
if (cur == nullptr)
{
return true;
}
if (cur->_col == RED&&cur->_parent->_col == RED)
{
cout << "违反规则,存在连续的红色节点" << endl;
return false;
}
return CheckRED_RED(cur->_left)
&& CheckRED_RED(cur->_right);
}
// 检查每条路径黑色节点的数量
bool CheckBlackNum(Node* cur, int blackNum, int benchmark)
{
if (cur == nullptr)
{
if (blackNum != benchmark)
{
cout << "黑色节点的数量不相等" << endl;
return false;
}
return true;
}
if (cur->_col == BLACK)
++blackNum;
return CheckBlackNum(cur->_left, blackNum, benchmark)
&& CheckBlackNum(cur->_right, blackNum, benchmark);
}
bool IsBalance()
{
if (_root == nullptr)
{
return true;
}
if (_root->_col == RED)// 检测根节点的颜色
{
cout << "违反规则根节点是红色" << endl;
return false;
}
// 算出最左路径的黑色节点的数量作为基准值
Node* cur = _root;
int benchmark = 0// 记录最左路径的黑色节点的数量
while (cur)
{
if (cur->_col == BLACK)
{
benchmark++;
}
cur = cur->_left;
}
int blackNum = 0;// 记录当前路径黑色节点的数量
return CheckRED_RED(_root) && CheckBlackNum(_root, blackNum, benchmark);
}
private:
Node* _root;
};
红黑树模板参数
为了满足set(K模型)和map(KV模型)的容器,我们把红黑树模板的第二个参数改为T
template<class K, class T>
class RBTree
这里的T不再仅仅是键值对中的成员,在set容器中表示第二个K
template<class K>
class set
{
private:
RBTree<K, K> _t;
};
在map容器中表示pair<K,V>
template<class K, class V>
class map
{
private:
RBTree<K, pair<K, V>> _t;
};
红黑树节点的修改
红黑树的节点不只是键值对,还可能是单值K,这里需要改变模板来表示不同的类型
template<class T>
struct RBTreeNode
{
RBTreeNode<T>* _left;// 左子节点
RBTreeNode<T>* _right;// 右子节点
RBTreeNode<T>* _parent; // 父节点
Colour _col;// 节点的颜色
T _data;// 节点的值
RBTreeNode(const T& data)
:_left(nullptr)
, _right(nullptr)
, _parent(nullptr)
, _col(RED)
, _data(data)
{}
};
模板参数中的仿函数
由于结点当中存储的是T,这个T可能是Key,也可能是<Key, Value>键值对。那么当我们需要进行结点的键值比较时该怎么办呢?
这里就需要用到仿函数了,利用仿函数将T中的K值取出来进行比较。
仿函数,就是使一个类的使用看上去像一个函数。其实现就是类中实现一个operator(),这个类就有了类似函数的行为,就是一个仿函数类了。
template<class K, class V>
class map
{
//仿函数
struct MapKeyOfT
{
const K& operator()(const pair<K, V>& kv) //返回键值对当中的键值Key
{
return kv.first;
}
};
private:
RBTree<K, pair<K, V>, MapKeyOfT> _t;
};
对于红黑树来说,它并不知道上层容器是map还是set,因此当需要进行两个结点键值的比较时,底层红黑树都会通过传入的仿函数来获取键值Key。
所以,set容器也需要仿函数
template<class K>
class set
{
//仿函数
struct SetKeyOfT
{
const K& operator()(const K& key) //返回键值Key
{
return key;
}
};
private:
RBTree<K, K, SetKeyOfT> _t;
};
仿函数创建后,当红黑树想要对节点的值进行比较时,都需要通过仿函数来获取节点的值。
例如寻找插入新节点的位置时就需要用到仿函数
pair<iterator,bool> Insert(const T& data)
{
Node* parent = nullptr;
Node* cur = _root;
KeyOfT kot;
while (cur)
{ // 插入节点比根节点大,往根节点右子树找
if (kot(cur->_data) < kot(data))
{
parent = cur;
cur = cur->_right;
}// 插入节点比根节点小,往根节点左子树找
else if (kot(cur->_data)>kot(data))
{
parent = cur;
cur = cur->_left;
}
else// 如果存在,直接返回,避免数据冗余
{
return make_pair(iterator(cur),false);
}
}
}
正向迭代器的实现
红黑树的跌点器实际上就是对节点指针的封装,里面只有一个成员变量指向节点的指针。
template<class T,class Ref,class Ptr>
struct RBTreeIterator
{
typedef RBTreeNode<T> Node;// 重命名节点
typedef RBTreeIterator<T, Ref, Ptr> Self;// 重命名迭代器
Node* _node;// 成员变量
RBTreeIterator(Node* node = nullptr)// 构造函数
:_node(node)
{}
}
对迭代器进行解引用操作时,直接返回对应结点数据的引用。
Ref operator*()
{
return _node->_data;
}
对迭代器进行 -> 操作时,直接返回对应结点数据的地址。
Ptr operator->()
{
return &_node->_data;//返回结点数据的地址
}
判断两个迭代器是否相等,直接判断迭代器封装结点是否相等
bool operator!=(const Self& s)const
{
return _node != s._node;
}
bool operator==(const Self& s)const
{
return _node == s._node;
}
迭代器的++操作,迭代器的++就是按照红黑树的中序遍历找到当前节点的下一个节点。
实现思路:
- 当前节点右子树不为空,++操作找到该节点右子树最左节点。
- 当前节点右子树为空,++操作往祖先节点遍历,找到子节点为父节点左孩子的父节点。
实现代码
Self& operator++()
{
if (_node->_right)
{
// 右子树中序第一个节点,也就是右子树的最左节点
Node* subLeft = _node->_right;
while (subLeft->_left)
{
subLeft = subLeft->_left;
}
_node = subLeft;
}
else
{
// 当前子树已经访问完了,要去找祖先访问,沿着到根节点的路径往上走,
// 找孩子是父亲左的那个父亲节点
Node* cur = _node;
Node* parent = cur->_parent;
while (parent&&parent->_right == cur)
{
cur = parent;
parent = parent->_parent;
}
_node = parent;
}
return *this;
}
迭代器的- -操作,迭代器的- -操作就是按照红黑树的中序遍历找到当前节点的上一个节点。
实现思路:
- 当前节点左子树不为空,- - 操作找到该节点左子树最右节点。
- 当前节点右子树为空,- - 操作往祖先节点遍历,找到子节点为父节点右孩子的父节点。
实现代码
Self& operator--()
{
if (_node->_left)
{
// 左子树中序最后一个节点,也就是左子树的最右节点
Node* subRight = _node->_left;
while (subRight->_right)
{
subRight = subRight->_right;
}
_node = subRight;
}
else
{
// 当前子树已经访问完了,要去找祖先访问,沿着到根节点的路径往上走,
// 找孩子是父亲右的那个父亲节点
Node* cur = _node;
Node* parent = cur->_parent;
while (parent&&parent->_left == cur)
{
cur = parent;
parent = parent->_parent;
}
_node = parent;
}
return *this;
}
正向迭代器实现后,我们需要在红黑树的实现中进行迭代器类型的typedef。需要注意的是,为了让外部能够使用typedef后的正向迭代器类型iterator,我们需要在public区域进行typedef。
还需要再红黑树中实现成员函数begin,end
- begin:返回中序遍历的第一个节点的迭代器,即最左节点的迭代器。
- end:返回中序遍历的最后一个节点的下一位置的迭代器,也就是nullptr
template<class K, class T,class KeyOfT>
class RBTree
{
typedef RBTreeNode<T> Node;// 重命名节点
public:
typedef RBTreeIterator<T, T&, T*> iterator;// 重命名迭代器
iterator begin()
{
//寻找最左结点
Node* left = _root;
while (left&&left->_left)
{
left = left->_left;
}
//返回最左结点的正向迭代器
return iterator(left);
}
iterator end()
{
return iterator(nullptr);
}
private:
Node* _root;
}
上述所实现的迭代器是有缺陷的,因为理论上我们对end()位置的正向迭代器进行- - 操作后,应该得到最后一个结点的迭代器,但我们实现end()时,是直接返回由nullptr构造得到的迭代器。
在C++SLT库实现逻辑如下
C++STL库当中实现红黑树时,在红黑树的根结点处增加了一个头结点,该头结点的左指针指向红黑树当中的最左结点,右指针指向红黑树当中的最右结点,父指针指向红黑树的根结点。
在该结构下,实现begin()时,直接用头结点的左孩子构造一个正向迭代器即可,,而实现end()时,直接用头结点构造出正向迭代器即可。此后,通过对逻辑的控制,就可以实现end()进行- - 操作后得到最后一个结点的迭代器。
set的模拟实现
set的模拟实现调用红黑树的接口就可以了
```cpp
namespace nzb
{
template<class K>
class set
{
// 仿函数
struct SetKeyOfT
{
const K& operator()(const K& key)
{
return key;
}
};
public:
typedef typename RBTree<K, K, SetKeyOfT>::iterator iterator;
iterator begin()
{
return _t.begin();
}
iterator end()
{
return _t.end();
}
pair<iterator, bool> insert(const K& key)
{
return _t.Insert(key);
}
private:
RBTree<K, K, SetKeyOfT> _t;
};
}
map的模拟实现
map的模拟实现的set一样调用红黑树即可
namespace nzb
{
template<class K,class V>
class map
{
// 仿函数
struct MapKeyOfT
{
const K& operator()(const pair<const K, V>& kv)
{
return kv.first;
}
};
public:
typedef typename RBTree<K, pair<const K, V>, MapKeyOfT>::iterator iterator;
iterator begin()
{
return _t.begin();
}
iterator end()
{
return _t.end();
}
pair<iterator, bool> insert(const pair<const K, V>& kv)
{
return _t.Insert(kv);
}
//map中需要对[]运算符重载
V& operator[](const K& key)
{
pair<iterator, bool> ret = _t.Insert(make_pair(key, V()));
return ret.first->second;
}
private:
RBTree<K, pair<const K, V>, MapKeyOfT> _t;
};
}
迭代器和红黑树完整代码
为了便于封装map和set我们对之前模拟实现的红黑数进行了调整,代码如下。
enum Colour
{
BLACK,
RED
};
template<class T>
struct RBTreeNode
{
RBTreeNode<T>* _left;
RBTreeNode<T>* _right;
RBTreeNode<T>* _parent;
Colour _col;
T _data;
RBTreeNode(const T& data)
:_left(nullptr)
, _right(nullptr)
, _parent(nullptr)
, _col(RED)
, _data(data)
{}
};
template<class T,class Ref,class Ptr>
struct RBTreeIterator
{
typedef RBTreeNode<T> Node;// 重命名节点
typedef RBTreeIterator<T, Ref, Ptr> Self;// 重命名迭代器
Node* _node;
RBTreeIterator(Node* node = nullptr)
:_node(node)
{}
Ref operator*()
{
return _node->_data;//返回结点数据的引用
}
Ptr operator->()
{
return &_node->_data;//返回结点数据的地址
}
Self& operator++()
{
if (_node->_right)
{
// 右子树中序第一个节点,也就是右子树的最左节点
Node* subLeft = _node->_right;
while (subLeft->_left)
{
subLeft = subLeft->_left;
}
_node = subLeft;
}
else
{
// 当前子树已经访问完了,要去找祖先访问,沿着到根节点的路径往上走,
// 找孩子是父亲左的那个父亲节点
Node* cur = _node;
Node* parent = cur->_parent;
while (parent&&parent->_right == cur)
{
cur = parent;
parent = parent->_parent;
}
_node = parent;
}
return *this;
}
Self& operator--()
{
if (_node->_left)
{
// 左子树中序最后一个节点,也就是左子树的最右节点
Node* subRight = _node->_left;
while (subRight->_right)
{
subRight = subRight->_right;
}
_node = subRight;
}
else
{
// 当前子树已经访问完了,要去找祖先访问,沿着到根节点的路径往上走,
// 找孩子是父亲右的那个父亲节点
Node* cur = _node;
Node* parent = cur->_parent;
while (parent&&parent->_left == cur)
{
cur = parent;
parent = parent->_parent;
}
_node = parent;
}
return *this;
}
bool operator!=(const Self& s)const
{
return _node != s._node;
}
bool operator==(const Self& s)const
{
return _node == s._node;
}
};
template<class K, class T,class KeyOfT>
class RBTree
{
typedef RBTreeNode<T> Node;// 重命名节点
public:
typedef RBTreeIterator<T, T&, T*> iterator;// 重命名迭代器
typedef RBTreeIterator<T, const T&, const T*> const_iterator;
iterator begin()
{
//寻找最左结点
Node* left = _root;
while (left&&left->_left)
{
left = left->_left;
}
//返回最左结点的正向迭代器
return iterator(left);
}
iterator end()
{
return iterator(nullptr);
}
RBTree()
:_root(nullptr)
{}
pair<iterator,bool> Insert(const T& data)
{
if (_root == nullptr)
{
_root = new Node(data);
_root->_col = BLACK;
return make_pair(iterator(_root),true);
}
Node* parent = nullptr;
Node* cur = _root;
KeyOfT kot;
while (cur)
{ // 插入节点比根节点大,往根节点右子树找
if (kot(cur->_data) < kot(data))
{
parent = cur;
cur = cur->_right;
}// 插入节点比根节点小,往根节点左子树找
else if (kot(cur->_data)>kot(data))
{
parent = cur;
cur = cur->_left;
}
else// 如果存在,直接返回,避免数据冗余
{
return make_pair(iterator(cur),false);
}
}
cur = new Node(data);
Node* newnode = cur;
cur->_col = RED;
if (kot(parent->_data) < kot(data))
{
parent->_right = cur;
cur->_parent = parent;
}
else
{
parent->_left = cur;
cur->_parent = parent;
}
// 控制近似平衡
while (parent&&parent->_col == RED)
{
Node* grandparent = parent->_parent;
if (parent == grandparent->_left)
{
Node* uncle = grandparent->_right;
// 情况一:uncle存在且为红,进行变色处理,并继续往上更新处理
if (uncle&&uncle->_col == RED)
{
uncle->_col = BLACK;
parent->_col = BLACK;
grandparent->_col = RED;
cur = grandparent;
parent = cur->_parent;
}// 情况二+三:uncle不存在,或者存在且为黑,需要旋转+变色处理
else
{
// 情况二:单旋+变色
if (cur == parent->_left)
{
RotateR(grandparent);
parent->_col = BLACK;
grandparent->_col = RED;
}
else// 情况三:双旋 + 变色
{
RotateL(parent);
RotateR(grandparent);
cur->_col = BLACK;
grandparent->_col = RED;
}
break;
}
}
else // (parent == grandfather->_right)
{
Node* uncle = grandparent->_left;
if (uncle&&uncle->_col == RED)
{
uncle->_col = BLACK;
parent->_col = BLACK;
grandparent->_col = RED;
cur = grandparent;
parent = cur->_parent;
}
else
{
if (parent->_right == cur)
{
RotateL(grandparent);
parent->_col = BLACK;
grandparent->_col = RED;
}
else
{
RotateR(parent);
RotateL(grandparent);
cur->_col = BLACK;
grandparent->_col = RED;
}
break;
}
}
}
_root->_col = BLACK;
return make_pair(iterator(newnode),true);
}
void RotateR(Node* parent)
{
Node* subL = parent->_left;
Node* subLR = subL->_right;
parent->_left = subLR;
if (subLR)
subLR->_parent = parent;
Node* ppNode = parent->_parent;
subL->_right = parent;
parent->_parent = subL;
if (parent == _root)
{
_root = subL;
subL->_parent = nullptr;
}
else
{
if (ppNode->_left == parent)
ppNode->_left = subL;
else
ppNode->_right = subL;
subL->_parent = ppNode;
}
}
void RotateL(Node* parent)
{
Node* subR = parent->_right;
Node* subRL = subR->_left;
parent->_right = subRL;
if (subRL)
subRL->_parent = parent;
Node* ppNode = parent->_parent;
subR->_left = parent;
parent->_parent = subR;
if (parent == _root)
{
_root = subR;
subR->_parent = nullptr;
}
else
{
if (ppNode->_left == parent)
{
ppNode->_left = subR;
}
else
{
ppNode->_right = subR;
}
subR->_parent = ppNode;
}
}
void _InOrder(Node* root)
{
if (root == nullptr)
{
return;
}
_InOrder(root->_left);
cout << root->_kv.first<<" ";
_InOrder(root->_right);
}
void InOrder()
{
_InOrder(_root);
cout << endl;
}
bool CheckRED_RED(Node* cur)
{
if (cur == nullptr)
{
return true;
}
if (cur->_col == RED&&cur->_parent->_col == RED)
{
cout << "违反规则,存在连续的红色节点" << endl;
return false;
}
return CheckRED_RED(cur->_left)
&& CheckRED_RED(cur->_right);
}
// 检查每条路径黑色节点的数量
bool CheckBlackNum(Node* cur, int blackNum, int benchmark)
{
if (cur == nullptr)
{
if (blackNum != benchmark)
{
cout << "黑色节点的数量不相等" << endl;
return false;
}
return true;
}
if (cur->_col == BLACK)
++blackNum;
return CheckBlackNum(cur->_left, blackNum, benchmark)
&& CheckBlackNum(cur->_right, blackNum, benchmark);
}
bool IsBalance()
{
if (_root == nullptr)
{
return true;
}
if (_root->_col == RED)
{
cout << "违反规则根节点是红色" << endl;
return false;
}
// 算出最左路径的黑色节点的数量作为基准值
Node* cur = _root;
int benchmark = 0;
while (cur)
{
if (cur->_col == BLACK)
{
benchmark++;
}
cur = cur->_left;
}
int blackNum = 0;
return CheckRED_RED(_root) && CheckBlackNum(_root, blackNum, benchmark);
}
private:
Node* _root;
};