红黑树,是一种二叉搜索树,但在每个结点上增加一个存储位表示结点的颜色,可以是Red或Black通过对任何一条从根到叶子的路径上各个结点着色方式的限制,红黑树确保没有一条路径会比其他路径长出俩倍,因而是接近平衡的。
通过颜色互斥来控制平衡
近似平衡,最长路径最多是最短路径的二倍
为了后续实现关联式容器简单,红黑树的实现中增加一个头结点,因为跟节点必须为黑色,为了与根节点进行区分,将头结点给成黑色,并且让头结点的pParent域指向红黑树的根节点,pLeft域指向红黑树中最小的节点,_pRight域指向红黑树中最大的节点
因为新节点的默认颜色是红色,因此:如果其parent节点的颜色是黑色,没有违反红黑树任何性质,则不需要调整;但当新插入节点的parenet节点颜色为红色时,就违反了性质三不能有连在一起的红色节点,
cur为当前节点,p->parent,g->grandfather,u->uncle
cur为红,p为红,g为黑,u存在且为红
注意:此时所看到的树,可能也是子树
cur为红,p为红,g为黑,u不存在/u存在且为黑
说明:
u的情况有两种
cur为红,p为红,g为黑,u不存在/u为黑
p为g的左孩子,cur为p的右孩子,则针对p做左单旋转;
相反,p为g的右孩子,cur为p的左孩子,则针对p做右单旋转,则转换成了情况2
(没封装版)
#pragma once
#include
using namespace std;
//red-black tree
enum Color
{
RED,
BLACK
};
template<class K,class V>
struct RBTreeNode
{
RBTreeNode<K, V>* _left;
RBTreeNode<K, V>* _right;
RBTreeNode<K, V>* _parent;
pair<K, V> _kv;
Color _col;
RBTreeNode(const pair<K,V>& kv)
:_left(nullptr)
, _right(nullptr)
, _parent(nullptr)
, _kv(kv)
, _col(RED)
{}
};
template<class K,class V>
struct _TreeIterator
{
typedef RBTreeNode<K, V> Node;
Node* _node;
_TreeIterator(Node* node)
:_node(node)
{}
//operator*();
//operator++();
//operator--();
};
template<class K,class V>
class RBTree
{
typedef RBTreeNode<K, V> Node;
public:
RBTree()
:_root(nullptr)
{}
void _Destory(Node* root)
{
if (root == nullptr)
{
return;
}
_Destory(root->_left);
_Destory(root->_right);
delete root;
}
~RBTree()
{
_Destory(_root);
_root = nullptr;
}
Node* Find(const K& key)
{
Node* cur = _root;
while (cur)
{
if (cur->_kv.first > key)
{
cur = cur->_left;
}
else if (cur->_kv.first < key)
{
cur = cur->_right;
}
else
{
return cur;
}
}
return nullptr;
}
pair<Node*, bool> Insert(const pair<K, V>& kv)
{
if (_root == nullptr)
{
_root = new Node(kv);
_root->_col = BLACK;
return make_pair(_root, 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 make_pair(cur, false);
}
}
Node* newnode = new Node(kv);
newnode->_col = RED;
if (parent->_kv.first < kv.first)
{
parent->_right = newnode;
newnode->_parent = parent;
}
else
{
parent->_left = newnode;
newnode->_parent = parent;
}
//插入的结点是黑色还是红色?
//插入红色结点,可能破坏规则3,但是影响不大
//插入黑色结点,一定破坏规则4,并且会影响其他路径,影响面很大
cur = newnode;
//如果父亲存在,且颜色为红色就需要处理
while (parent && parent->_col == RED)
{
//关键看叔叔
Node* grandfather = parent->_parent;
if (parent == grandfather->_left)
{
Node* uncle = grandfather->_right;
if (uncle && uncle->_col == RED)
{
//情况1:uncle 存在且为红
//把parent和uncle变黑,grandfather变红
parent->_col = uncle->_col = BLACK;
grandfather->_col = RED;
//继续往上处理
cur = grandfather;
parent = cur->_parent;
}
else
{
//情况2+3
//uncle不存在或uncle存在且为黑
if (cur == parent->_left)
{
//情况2:需要右单旋
RotateR(grandfather);
grandfather->_col = RED;
parent->_col = BLACK;
}
else
{
//情况3:左右双旋
RotateL(parent);
RotateR(grandfather);
cur->_col = BLACK;
grandfather->_col = RED;
}
break;
}
}
else//parent == grandfather->right
{
Node* uncle = grandfather->_left;
if (uncle && uncle->_col == RED)
{
//情况一
uncle->_col = parent->_col = BLACK;
grandfather->_col = RED;
cur = grandfather;
parent = cur->_parent;
}
else
{
//情况2+情况3
if (cur == parent->_right)
{
RotateL(grandfather);
parent->_col = BLACK;
grandfather->_col = RED;
}
else // cur == parent->_left
{
RotateR(parent);
RotateL(grandfather);
cur->_col = BLACK;
grandfather->_col = RED;
}
//插入结束
break;
}
}
}
_root->_col = BLACK;
return make_pair(newnode, true);
}
void RotateR(Node* parent)
{
Node* subl = parent->_left;
Node* sublr = subl->_right;
parent->_left = sublr;
if (sublr)
{
sublr->_parent = parent;
}
subl->_right = parent;
Node* parentparent = parent->_parent;
parent->_parent = subl;
if (parent == _root)
{
//是一个独立的树
_root = subl;
_root->_parent = nullptr;
}
else
{
//只是子树,parent还有parent
if (parentparent->_left == parent)
{
parentparent->_left = subl;
}
else
{
parentparent->_right = subl;
}
subl->_parent = parentparent;
}
}
void RotateL(Node* parent)
{
Node* subr = parent->_right;
Node* subrl = subr->_left;
parent->_right = subrl;
if (subrl)
{
subrl->_parent = parent;
}
Node* parentparent = parent->_parent;
subr->_left = parent;
parent->_parent = subr;
if (parent == _root)
{
//是独立的树
_root = subr;
_root->_parent = nullptr;
}
else
{
//是子树
if (parentparent->_left == parent)
parentparent->_left = subr;
else
parentparent->_right = subr;
subr->_parent = parentparent;
}
}
bool _CheckBalance(Node* root, int blacknum, int count)
{
if (root == nullptr)
{
if (count != blacknum)
{
cout << "黑色结点数目不相等" << endl;
return false;
}
return true;
}
if (root->_col == RED && root->_parent->_col == RED)
{
cout << "存在连续红色" << endl;
return false;
}
if (root->_col == BLACK)
{
count++;
}
return _CheckBalance(root->_left,blacknum,count)
&& _CheckBalance(root->_right,blacknum,count);
}
bool CheckBalance()
{
if (_root == nullptr)
{
return true;
}
if (_root->_col == RED)
{
cout << "root is red" << endl;
return false;
}
//找最左路径做参考值
int blacknum = 0;
Node* left = _root;
while (left)
{
if (left->_col == BLACK)
{
blacknum++;
}
left = left->_left;
}
int count = 0;
return _CheckBalance(_root, blacknum, count);
}
void _Inorder(Node* root)
{
if (root == nullptr)
{
return;
}
_Inorder(root->_left);
cout << root->_kv.first <<"->"<<root->_kv.second<< endl ;
_Inorder(root->_right);
}
void Inorder()
{
_Inorder(_root);
}
private:
Node* _root;
};
#pragma once
// 反向迭代器--迭代器适配器
template<class Iterator>
struct ReverseIterator
{
typedef typename Iterator::reference Ref;
typedef typename Iterator::pointer Ptr;
typedef ReverseIterator<Iterator> Self;
Iterator _it;
ReverseIterator(Iterator it)
:_it(it)
{}
Ref operator*()
{
return *_it;
}
Ptr operator->()
{
return _it.operator->();
}
Self& operator++()
{
--_it;
return *this;
}
Self& operator--()
{
++_it;
rteurn *this;
}
bool operator!=(const Self& s) const
{
return _it != s._it;
}
bool operator==(const Self& s) const
{
return _it == s._it;
}
};
#pragma once
#include
using namespace std;
#include "Iterator.h"
enum Colour
{
RED,
BLACK,
};
//red-black
template<class T>
struct RBTreeNode
{
RBTreeNode<T>* _left;
RBTreeNode<T>* _right;
RBTreeNode<T>* _parent;
T _data;
Colour _col;
RBTreeNode(const T& x)
:_left(nullptr)
, _right(nullptr)
, _parent(nullptr)
, _data(x)
, _col(RED)
{}
};
template<class T, class Ref, class Ptr>
struct __TreeIterator
{
typedef Ref reference;
typedef Ptr pointer;
typedef RBTreeNode<T> Node;
typedef __TreeIterator<T, Ref, Ptr> Self;
Node* _node;
__TreeIterator(Node* node)
:_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* left = _node->_right;
while (left->_left)
{
left = left->_left;
}
_node = left;
}
else
{
// 找祖先里面孩子不是父亲的右的那个
// 因为 cur 右为空,说明cur所在的子树已经访问完了
// cur是parent的右的,说明parent也访问完了,继续往上去找
Node* cur = _node;
Node* parent = cur->_parent;
while (parent && cur == parent->_right)
{
cur = cur->_parent;
parent = parent->_parent;
}
_node = parent;
}
return *this;
}
Self& operator--()
{
if (_node->_left)
{
// 左子树的最右节点
Node* right = _node->_left;
while (right->_right)
{
right = right->_right;
}
_node = right;
}
else
{
Node* cur = _node;
Node* parent = cur->_parent;
while (parent && cur == parent->_left)
{
cur = parent;
parent = parent->_parent;
}
_node = parent;
}
return *this;
}
};
template<class K, class T, class KeyOfT>
class RBTree
{
typedef RBTreeNode<T> Node;
public:
typedef __TreeIterator < T, T&, T* > iterator;
typedef __TreeIterator < T, const T&, const T* > const_iterator;
typedef ReverseIterator<iterator> reverse_iterator;
reverse_iterator rbegin()
{
Node* right = _root;
while (right && right->_right)
{
right = right->_right;
}
return reverse_iterator(iterator(right));
}
reverse_iterator rend()
{
return reverse_iterator(iterator(nullptr));
}
iterator begin()
{
Node* left = _root;
while (left && left->_left)
{
left = left->_left;
}
return iterator(left);
}
iterator end()
{
return iterator(nullptr);
}
RBTree()
:_root(nullptr)
{}
void Destory(Node* root)
{
if (root == nullptr)
{
return;
}
Destory(root->_left);
Destory(root->_right);
delete root;
}
~RBTree()
{
Destory(_root);
_root = nullptr;
}
Node* Find(const K& key)
{
KeyOfT kot;
Node* cur = _root;
while (cur)
{
if (kot(cur->_data) > key)
{
cur = cur->_left;
}
else if (kot(cur->_data) < key)
{
cur = cur->_right;
}
else
{
return cur;
}
}
return nullptr;
}
pair<iterator, bool> Insert(const T& data)
{
if (_root == nullptr)
{
_root = new Node(data);
_root->_col = BLACK;
return make_pair(iterator(_root), true);
}
KeyOfT kot;
Node* parent = nullptr;
Node* cur = _root;
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);
}
}
Node* newnode = new Node(data);
newnode->_col = RED;
if (kot(parent->_data) < kot(data))
{
parent->_right = newnode;
newnode->_parent = parent;
}
else
{
parent->_left = newnode;
newnode->_parent = parent;
}
cur = newnode;
// 如果父亲存在,且颜色为红色就需要处理
while (parent && parent->_col == RED)
{
Node* grandfather = parent->_parent;
// 关键是看叔叔
if (parent == grandfather->_left)
{
Node* uncle = grandfather->_right;
// 情况1:uncle存在且为红
if (uncle && uncle->_col == RED)
{
parent->_col = uncle->_col = BLACK;
grandfather->_col = RED;
// 继续往上处理
cur = grandfather;
parent = cur->_parent;
}
else // 情况2+3:uncle不存在 uncle存在且为黑
{
// 情况2:单旋
if (cur == parent->_left)
{
RotateR(grandfather);
grandfather->_col = RED;
parent->_col = BLACK;
}
else // 情况3:双旋
{
RotateL(parent);
RotateR(grandfather);
cur->_col = BLACK;
grandfather->_col = RED;
}
break;
}
}
else // parent == grandfather->_right
{
Node* uncle = grandfather->_left;
// 情况1:
if (uncle && uncle->_col == RED)
{
uncle->_col = parent->_col = BLACK;
grandfather->_col = RED;
cur = grandfather;
parent = cur->_parent;
}
else // 情况2:+ 情况3:
{
if (cur == parent->_right)
{
RotateL(grandfather);
parent->_col = BLACK;
grandfather->_col = RED;
}
else // cur == parent->_left
{
RotateR(parent);
RotateL(grandfather);
cur->_col = BLACK;
grandfather->_col = RED;
}
// 插入结束
break;
}
}
}
_root->_col = BLACK;
return make_pair(iterator(newnode), true);
}
void RotateL(Node* parent)
{
Node* subR = parent->_right;
Node* subRL = subR->_left;
parent->_right = subRL;
if (subRL)
{
subRL->_parent = parent;
}
subR->_left = parent;
Node* parentParent = parent->_parent;
parent->_parent = subR;
if (parent == _root)
{
_root = subR;
_root->_parent = nullptr;
}
else
{
if (parentParent->_left == parent)
{
parentParent->_left = subR;
}
else
{
parentParent->_right = subR;
}
subR->_parent = parentParent;
}
}
void RotateR(Node* parent)
{
Node* subL = parent->_left;
Node* subLR = subL->_right;
parent->_left = subLR;
if (subLR)
subLR->_parent = parent;
subL->_right = parent;
Node* parentParent = parent->_parent;
parent->_parent = subL;
if (parent == _root)
{
_root = subL;
_root->_parent = nullptr;
}
else
{
if (parentParent->_left == parent)
parentParent->_left = subL;
else
parentParent->_right = subL;
subL->_parent = parentParent;
}
}
bool _CheckBlance(Node* root, int blackNum, int count)
{
if (root == nullptr)
{
if (count != blackNum)
{
cout << "黑色节点的数量不相等" << endl;
return false;
}
return true;
}
if (root->_col == RED && root->_parent->_col == RED)
{
cout << "存在连续的红色节点" << endl;
return false;
}
if (root->_col == BLACK)
{
count++;
}
return _CheckBlance(root->_left, blackNum, count)
&& _CheckBlance(root->_right, blackNum, count);
}
bool CheckBlance()
{
if (_root == nullptr)
{
return true;
}
if (_root->_col == RED)
{
cout << "根节点是红色的" << endl;
return false;
}
// 找最左路径做黑色节点数量参考值
int blackNum = 0;
Node* left = _root;
while (left)
{
if (left->_col == BLACK)
{
blackNum++;
}
left = left->_left;
}
int count = 0;
return _CheckBlance(_root, blackNum, count);
}
/*void _InOrder(Node* root)
{
if (root == nullptr)
{
return;
}
_InOrder(root->_left);
cout << root->_kv.first << ":"<_kv.second<_right);
}*/
/*void InOrder()
{
_InOrder(_root);
cout << endl;
}
*/
private:
Node* _root;
};
#pragma once
#include "RBT2.h"
namespace rbt{
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;
typedef typename RBTree<K, pair<const K, V>, MapKeyOfT>::reverse_iterator reverse_iterator;
reverse_iterator rbegin()
{
return _t.rbegin();
}
reverse_iterator rend()
{
return _t.rend();
}
iterator begin()
{
return _t.begin();
}
iterator end()
{
return _t.end();
}
pair<iterator, bool> insert(const pair<const K, V>& kv)
{
return _t.Insert(kv);
}
V& operator[](const K& key)
{
pair<iterator, bool> ret = insert(make_pair(key, V()));
return ret.first->second;
}
private:
RBTree<K, pair<const K, V>, MapKeyOfT> _t;
};
}
#pragma once
#include "RBT2.h"
namespace rbt
{
template<class K>
class Set
{
struct SetKeyOfT
{
const K& operator()(const K& key)
{
return key;
}
};
public:
typedef typename RBTree<K, K, SetKeyOfT>::iterator iterator;
typedef typename RBTree<K, K, SetKeyOfT>::reverse_iterator reverse_iterator;
reverse_iterator rbegin()
{
return _t.rbegin();
}
reverse_iterator rend()
{
return _t.rend();
}
iterator begin()
{
return _t.begin();
}
iterator end()
{
return _t.end();
}
pair<iterator, bool> insert(const K& k)
{
return _t.Insert(k);
}
private:
RBTree<K, K, SetKeyOfT> _t;
};
}
#pragma once
#include
#include "Iterator.h"
namespace rbt
{
template<class T>
struct _list_node
{
T _val;
_list_node<T>* _next;
_list_node<T>* _prev;
_list_node(const T& val = T())
:_val(val)
, _prev(nullptr)
, _next(nullptr)
{}
};
// typedef _list_iterartor iterator;
// typedef _list_iterartor const_iterator;
template<class T, class Ref, class Ptr>
struct _list_iterartor
{
typedef Ref reference;
typedef Ptr pointer;
typedef _list_node<T> node;
typedef _list_iterartor<T, Ref, Ptr> self;
node* _pnode;
_list_iterartor(node* pnode)
:_pnode(pnode)
{}
// 拷贝构造、operator=、析构我们不写,编译器默认生成就可以用
// T& operator*() iterator 可读可写
// const T& operator*() const_iterator 可读可写
Ref operator*()
{
return _pnode->_val;
}
Ptr operator->()
{
return &_pnode->_val;
}
bool operator!=(const self& s) const
{
return _pnode != s._pnode;
}
bool operator==(const self& s) const
{
return _pnode == s._pnode;
}
// ++it -> it.operator++(&it)
self& operator++()
{
_pnode = _pnode->_next;
return *this;
}
// it++ -> it.operator++(&it, 0)
self operator++(int)
{
self tmp(*this);
_pnode = _pnode->_next;
return tmp;
}
self& operator--()
{
_pnode = _pnode->_prev;
return *this;
}
self operator--(int)
{
self tmp(*this);
_pnode = _pnode->_prev;
return tmp;
}
};
template<class T>
class list
{
typedef _list_node<T> node;
public:
typedef _list_iterartor<T, T&, T*> iterator;
typedef _list_iterartor<T, const T&, const T*> const_iterator;
typedef ReverseIterator<iterator> reverse_iterator;
reverse_iterator rbegin()
{
return reverse_iterator(iterator(_head->_prev));
}
reverse_iterator rend()
{
return reverse_iterator(iterator(_head));
}
iterator begin()
{
return iterator(_head->_next);
}
const_iterator begin() const
{
return const_iterator(_head->_next);
}
iterator end()
{
return iterator(_head);
}
const_iterator end() const
{
return const_iterator(_head);
}
list()
{
//_head = new node(T());
_head = new node;
_head->_next = _head;
_head->_prev = _head;
}
// copy(lt)
list(const list<T>& lt)
{
_head = new node;
_head->_next = _head;
_head->_prev = _head;
for (const auto& e : lt)
{
push_back(e);
}
}
//copy = lt1;
/* list& operator=(const list& lt)
{
if (this != <)
{
clear();
for (const auto& e : lt)
{
push_back(e);
}
}
return *this;
}*/
// copy = lt1;
list<T>& operator=(list<T> lt)
{
swap(_head, lt._head);
return *this;
}
~list()
{
clear();
delete _head;
_head = nullptr;
}
void clear()
{
iterator it = begin();
while (it != end())
{
//it = erase(it);
erase(it++);
}
}
void push_back(const T& x)
{
insert(end(), x);
}
void push_front(const T& x)
{
insert(begin(), x);
}
void pop_back()
{
erase(--end());
}
void pop_front()
{
erase(begin());
}
void insert(iterator pos, const T& x)
{
assert(pos._pnode);
node* cur = pos._pnode;
node* prev = cur->_prev;
node* newnode = new node(x);
// prev newnode cur
prev->_next = newnode;
newnode->_prev = prev;
newnode->_next = cur;
cur->_prev = newnode;
}
iterator erase(iterator pos)
{
assert(pos._pnode);
assert(pos != end());
node* prev = pos._pnode->_prev;
node* next = pos._pnode->_next;
delete pos._pnode;
prev->_next = next;
next->_prev = prev;
return iterator(next);
}
bool empty()
{
return begin() == end();
}
size_t size()
{
size_t sz = 0;
iterator it = begin();
while (it != end())
{
++sz;
++it;
}
return sz;
}
private:
node* _head;
//size_t _size;
};
void PrintList(const list<int>& lt)
{
list<int>::const_iterator it = lt.begin();
while (it != lt.end())
{
// *it += 1; // ?
cout << *it << " ";
++it;
}
cout << endl;
}
class Date
{
public:
int _year = 0;
int _month = 1;
int _day = 1;
};
void test_list1()
{
list<int> lt;
lt.push_back(1);
lt.push_back(2);
lt.push_back(3);
lt.push_back(4);
list<int>::iterator it = lt.begin();
while (it != lt.end())
{
*it += 1;
cout << *it << " ";
++it;
}
cout << endl;
for (auto e : lt)
{
cout << e << " ";
}
cout << endl;
PrintList(lt);
}
void test_list2()
{
list<Date> lt;
lt.push_back(Date());
lt.push_back(Date());
lt.push_back(Date());
list<Date>::iterator it = lt.begin();
while (it != lt.end())
{
//cout << (*it)._year << " " << (*it)._month <<" " <<(*it)._day<
cout << it->_year << " " << it->_month << " " << it->_day << endl;
++it;
}
cout << endl;
Date d;
Date* p = &d;
(*p)._year = 100;
p->_year = 100;
}
void test_list3()
{
list<int> lt;
lt.push_back(1);
lt.push_back(2);
lt.push_back(3);
lt.push_back(4);
PrintList(lt);
list<int> copy(lt);
PrintList(copy);
list<int> lt1;
lt1.push_back(10);
lt1.push_back(20);
copy = lt1;
PrintList(copy);
PrintList(lt1);
lt.clear();
PrintList(lt);
}
}