目录
1.AVL树
1.1.AVL树的概念
二叉搜索树虽可以缩短查找的效率,但如果数据有序或接近有序二叉搜索树将退化为单支树,查找元素相当于在顺序表中搜索元素,效率低下。因此,两位俄罗斯的数学家G.M.Adelson-Velskii和E.M.Landis在1962年发明了一种解决上述问题的方法:当向二叉搜索树中插入新结点后,如果能保证每个结点的左右子树高度之差的绝对值不超过1(需要对树中的结点进行调整),即可降低树的高度,从而减少平均搜索长度。
一棵AVL树或者是空树,或者是具有以下性质的二叉搜索树:
它的左右子树都是AVL树
左右子树高度之差(简称平衡因子)的绝对值不超过1(-1/0/1)
如果一棵二叉搜索树是高度平衡的,它就是AVL树。如果它有n个结点,其高度可保持在
,搜索时间复杂度
下面四棵树,一二三是AVL树,每个结点都满足其左右子树高度差的绝对值不超过1,四不是AVL树,因为其3结点的左子树高度是2,右子树高度是0,高度差的绝对值为2
可以看出,相比满二叉树,完全二叉树最后一层会缺一些结点,而AVL树最后两层会缺一些结点。
1.2.AVL树节点的定义
AVL树节点的定义:
template<class K, class V> struct AVLTreeNode { pair<K, V> _kv; AVLTreeNode<K, V>* _left; AVLTreeNode<K, V>* _right; AVLTreeNode<K, V>* _parent; // 右子树-左子树的高度差 int _bf; // balance factor AVLTreeNode(const pair<K, V>& kv) :_kv(kv) , _left(nullptr) , _right(nullptr) , _parent(nullptr) , _bf(0) {} // AVL树并没有规定必须要设计平衡因子 // 只是一个实现的选择,方便控制平衡 };
注:
1.AVL树使用三叉链,每个树结点中使用_parent成员变量保存其父节点的地址。
2.树节点中有一个_bf成员变量,该成员变量是balance factor的缩写,记录该节点右子树-左子树的高度差。AVL树并没有规定必须要设计平衡因子,这里使用平衡因子只是一个实现的选择,方便控制平衡。
1.3.AVL树的插入
AVL树就是在二叉搜索树的基础上引入了平衡因子,因此AVL树也可以看成是二叉搜索树。那么AVL树的插入过程可以分为两步:1. 按照二叉搜索树的方式插入新节点2. 调整节点的平衡因子。具体的说是判断是否违反平衡规则,如果违反就需要处理:旋转注:
1.在调整节点的平衡因子步骤中,每插入一个结点,更新新插入结点的祖先的平衡因子,然后对祖先结点进行判断,如果没有结点违反平衡规则就结束了,如果有结点违反平衡规则,那么就不平衡了需要旋转处理。2.如何更新新插入结点的祖先的平衡因子?例子:如下图一所示,如果新插入结点在结点9的右边,则结点9的_bf由0变成1,结点8的_bf由1变成2。如下图二所示,如果新插入结点在结点9的左边,则结点9的_bf由0变成-1,结点8的_bf由1变成2。如下图三所示,如果新插入结点在结点8的左边,则结点8的_bf由1变成0。沿着祖先路径更新,其每一次父节点平衡因子更新,步骤为:
第一步,判断parent指向结点的平衡因子如何更新:如果cur==parent->right新增结点等于父结点的右,parent->_bf++父结点的平衡因子++;如果cur==parent->left新增结点等于父结点的左,parent->_bf--父结点的平衡因子--。第二步,判断是否还继续往上更新(参考下图的原则):如果此时parent->_bf==1,说明原来是0,现在右子树变高了,parent指向结点的子树高度变了,继续往上更新;如果此时parent->_bf==-1,说明原来是0,现在左子树变高了,parent指向结点的子树高度变了,继续往上更新,如果此时parent->_bf==0,说明原来是1或-1,现在左子树和右子树高度相同(新插入结点填上了矮的那边),parent指向结点的子树高度不变,更新结束;如果此时parent->_bf==2或-2,说明原来是1或-1,插入结点导致本来高的一边又变高了,那么parent指向结点的子树违反平衡树规则,停止更新,旋转子树。
1.4.AVL树的旋转
旋转原则:
1.保持搜索树的规则
2.子树变的平衡
如果在一棵原本是平衡的AVL树中插入一个新节点,可能造成不平衡,此时必须调整树的结构,使之平衡化。根据节点插入位置的不同,AVL树的旋转分为四种:左单旋、右单旋、先左单旋再右单旋、先右单旋再左单旋。
1.新节点插入较高右子树的右侧---右右:左单旋左单旋:(1)b部分变成30的右子树(2)30变成60的左子树(3)60变成这个子树的根注:1.左单旋符合旋转的原则2.插入新节点,沿着新节点祖先路径往上更新平衡因子时,如果parent指向的父节点平衡因子为2,cur指向的子节点平衡因子为1时,进行左单旋左单旋代码:
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; _root->_parent = nullptr; } else { if (parent == ppNode->_left) { ppNode->_left = subR; } else { ppNode->_right = subR; } subR->_parent = ppNode; } // 更新平衡因子 parent->_bf = 0; subR->_bf = 0; }
注:
1.我们分别使用parent、subR、subRL指向旋转根节点30、旋转根节点右结点60、b部分,然后进行旋转,如下图所示2.还要注意的几点:
(1)我们用的是三叉链,将父节点和子节点链接既要让父节点指向子节点,也要让子节点指向父节点。
(2)parent和subR不可能是空,subRL有可能是空,要判断subRL是否为空。
(3)parent指向的结点如果是树的根,那么经过左单旋后subR指向的结点要更新成树的根。parent指向的结点如果是整个树局部子树的根,那么经过左单旋后原本parent指向结点的父节点要指向subR指向的结点。
(4)旋转完后要更新parent指针和subR指针指向结点的平衡因子。
(5)旋转前parent指向的结点如果是整个树局部子树的根,不需要再对旋转前parent指针指向结点的父节点及其上面结点更新平衡因子,因为经过插入和旋转,插入和旋转前后局部子树的高度都是h+2,对旋转前parent指针指向结点的父节点及其上面结点的平衡因子没有影响。
2. 新节点插入较高左子树的左侧---左左:右单旋右单旋:(1)b部分变成60的左子树(2)60变成30的右子树(3)30变成这个子树的根注:1.右单旋符合旋转的原则2.插入新节点,沿着新节点祖先路径往上更新平衡因子时,如果parent指向的父节点平衡因子为-2,cur指向的子节点平衡因子为-1时,进行右单旋右单旋代码:
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; _root->_parent = nullptr; } else { if (ppNode->_left == parent) { ppNode->_left = subL; } else { ppNode->_right = subL; } subL->_parent = ppNode; } subL->_bf = parent->_bf = 0; }
注:
1.我们分别使用parent、subL、subLR指向旋转根节点60、旋转根节点左结点30、b部分,然后进行旋转,如下图所示2.还要注意的几点:
(1)我们用的是三叉链,将父节点和子节点链接既要让父节点指向子节点,也要让子节点指向父节点。
(2)parent和subL不可能是空,subLR有可能是空,要判断subLR是否为空。
(3)parent指向的结点如果是树的根,那么经过右单旋后subL指向的结点要更新成树的根。parent指向的结点如果是整个树局部子树的根,那么经过右单旋后原本parent指向结点的父节点要指向subL指向的结点。
(4)旋转完后要更新parent指针和subL指针指向结点的平衡因子。
(5)旋转前parent指向的结点如果是整个树局部子树的根,不需要再对旋转前parent指针指向结点的父节点及其上面结点更新平衡因子,因为经过插入和旋转,插入和旋转前后局部子树的高度都是h+2,对旋转前parent指针指向结点的父节点及其上面结点的平衡因子没有影响。
3.新节点插入较高左子树的右侧---左右:先左单旋再右单旋左右双旋:(1)先左单旋(2)后右单旋注:1.左右双旋符合旋转的原则2.插入新节点,沿着新节点祖先路径往上更新平衡因子时,如果parent指向的父节点平衡因子为-2,cur指向的子节点平衡因子为1时,进行左右双旋左右双旋代码:void RotateLR(Node* parent) { Node* subL = parent->_left; Node* subLR = subL->_right; int bf = subLR->_bf; RotateL(parent->_left); RotateR(parent); // 更新平衡因子 if (bf == 0) { parent->_bf = 0; subL->_bf = 0; subLR->_bf = 0; } else if (bf == 1) { parent->_bf = 0; subL->_bf = -1; subLR->_bf = 0; } else if (bf == -1) { parent->_bf = 1; subL->_bf = 0; subLR->_bf = 0; } else { // subLR->_bf旋转前就有问题 assert(false); } }
注:1.我们分别使用parent、subL、subLR指向旋转根节点90、旋转根节点左结点30、旋转根节点左结点的右节点60,然后进行旋转,如下图所示2.还要注意的几点:
(1)我们用的是三叉链,将父节点和子节点链接既要让父节点指向子节点,也要让子节点指向父节点。
(2)左右双选的代码可以先复用左单旋再复用右单旋来实现,但是使用左单旋和右单旋的代码,会更新对应结点的平衡因子,最终会将parent、subL、subLR指向结点的平衡因子更新为0,但是从上面总览图中h=0的一种情况和h>0的两种情况左右双旋的结果来看,只有h=0的那一种情况左右双旋后的结果三个指针指向结点平衡因子为0,其余两种情况都有平衡因子不为0的结点,所以左右双旋后还需要更新平衡因子。
(3)旋转完后要更新parent、subL、subLR指针指向结点的平衡因子,我们使用subLR指针指向结点的平衡因子来区别判断三种情况,如果subLR指针指向结点的平衡因子为0,那就是h=0的情况,如果subLR指针指向结点的平衡因子为-1,那就是h>0且b部分插入新节点的情况,如果subLR指针指向结点的平衡因子为1,那就是h>0且c部分插入新节点的情况。
(4)旋转前parent指向的结点如果是整个树局部子树的根,不需要再对旋转前parent指针指向结点的父节点及其上面结点更新平衡因子,因为经过插入和旋转,插入和旋转前后局部子树的高度都是h+2,对旋转前parent指针指向结点的父节点及其上面结点的平衡因子没有影响。
4.新节点插入较高右子树的左侧---右左:先右单旋再左单旋右左双旋:(1)先右单旋(2)后左单旋注:1.右左双旋符合旋转的原则2.插入新节点,沿着新节点祖先路径往上更新平衡因子时,如果parent指向的父节点平衡因子为2,cur指向的子节点平衡因子为-1时,进行右左双旋右左双旋代码:void RotateRL(Node* parent) { Node* subR = parent->_right; Node* subRL = subR->_left; int bf = subRL->_bf; RotateR(parent->_right); RotateL(parent); if (bf == 0) { subRL->_bf = 0; parent->_bf = 0; subR->_bf = 0; } else if (bf == 1) { subRL->_bf = 0; parent->_bf = -1; subR->_bf = 0; } else if (bf == -1) { subRL->_bf = 0; parent->_bf = 0; subR->_bf = 1; } else { // subLR->_bf旋转前就有问题 assert(false); } }
注:
1.我们分别使用parent、subR、subRL指向旋转根节点30、旋转根节点右结点90、旋转根节点右结点的左节点60,然后进行旋转,如下图所示2.还要注意的几点:
(1)我们用的是三叉链,将父节点和子节点链接既要让父节点指向子节点,也要让子节点指向父节点。
(2)右左双选的代码可以先复用右单旋再复用左单旋来实现,但是使用右单旋和左单旋的代码,会更新对应结点的平衡因子,最终会将parent、subR、subRL指向结点的平衡因子更新为0,但是从上面总览图中h=0的一种情况和h>0的两种情况右左双旋的结果来看,只有h=0的那一种情况左右双旋后的结果三个指针指向结点平衡因子为0,其余两种情况都有平衡因子不为0的结点,所以右左双旋后还需要更新平衡因子。
(3)旋转完后要更新parent、subR、subRL指针指向结点的平衡因子,我们使用subRL指针指向结点的平衡因子来区别判断三种情况,如果subRL指针指向结点的平衡因子为0,那就是h=0的情况,如果subRL指针指向结点的平衡因子为1,那就是h>0且c部分插入新节点的情况,如果subRL指针指向结点的平衡因子为-1,那就是h>0且b部分插入新节点的情况。
(4)旋转前parent指向的结点如果是整个树局部子树的根,不需要再对旋转前parent指针指向结点的父节点及其上面结点更新平衡因子,因为经过插入和旋转,插入和旋转前后局部子树的高度都是h+2,对旋转前parent指针指向结点的父节点及其上面结点的平衡因子没有影响。
1.5.AVL树插入和旋转代码实现
AVLtree.h文件:
#pragma once
#include <assert.h>
#include <vector>
#include <queue>
#include <time.h>
template<class K, class V>
struct AVLTreeNode
{
pair<K, V> _kv;
AVLTreeNode<K, V>* _left;
AVLTreeNode<K, V>* _right;
AVLTreeNode<K, V>* _parent;
// 右子树-左子树的高度差
int _bf; // balance factor
AVLTreeNode(const pair<K, V>& kv)
:_kv(kv)
, _left(nullptr)
, _right(nullptr)
, _parent(nullptr)
, _bf(0)
{}
// AVL树并没有规定必须要设计平衡因子
// 只是一个实现的选择,方便控制平衡
};
template<class K, class V>
class AVLTree
{
typedef AVLTreeNode<K, V> Node;
public:
// Find
// Erase
bool Insert(const pair<K, V>& kv)
{
// 1、搜索树的规则插入
// 2、看是否违反平衡规则,如果违反就需要处理:旋转
if (_root == nullptr)
{
_root = new Node(kv);
_root->_bf = 0;
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);
if (parent->_kv.first < kv.first)
{
parent->_right = cur;
}
else
{
parent->_left = cur;
}
cur->_parent = parent;
// ...
// 更新平衡因子
while (parent) // 最远要更新根
{
if (cur == parent->_right)
{
parent->_bf++;
}
else
{
parent->_bf--;
}
// 是否继续更新?
if (parent->_bf == 0) // 1 or -1 -》 0 插入节点填上矮的那边
{
// 高度不变,更新结束
break;
}
else if (parent->_bf == 1 || parent->_bf == -1)
// 0 -》 1 或 -1 插入节点导致一边变高了
{
// 子树的高度变了,继续更新祖先
cur = cur->_parent;
parent = parent->_parent;
}
else if (parent->_bf == 2 || parent->_bf == -2)
// -1 or 1 -》 2 或 -2 插入节点导致本来高一边又变高了
{
// 子树不平衡 -- 需要旋转处理
if (parent->_bf == 2 && cur->_bf == 1) // 左单旋
{
RotateL(parent);
}
else if (parent->_bf == -2 && cur->_bf == -1) // 右单旋
{
RotateR(parent);
}
else if (parent->_bf == -2 && cur->_bf == 1) // 左右双旋
{
RotateLR(parent);
}
else if (parent->_bf == 2 && cur->_bf == -1) // 右左双旋
{
RotateRL(parent);
}
break;
}
else
{
// 插入之前AVL就存在不平衡子树,|平衡因子| >= 2的节点
assert(false);
}
}
return true;
}
private:
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;
_root->_parent = nullptr;
}
else
{
if (parent == ppNode->_left)
{
ppNode->_left = subR;
}
else
{
ppNode->_right = subR;
}
subR->_parent = ppNode;
}
// 更新平衡因子
parent->_bf = 0;
subR->_bf = 0;
}
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;
_root->_parent = nullptr;
}
else
{
if (ppNode->_left == parent)
{
ppNode->_left = subL;
}
else
{
ppNode->_right = subL;
}
subL->_parent = ppNode;
}
subL->_bf = parent->_bf = 0;
}
void RotateLR(Node* parent)
{
Node* subL = parent->_left;
Node* subLR = subL->_right;
int bf = subLR->_bf;
RotateL(parent->_left);
RotateR(parent);
// 更新平衡因子
if (bf == 0)
{
parent->_bf = 0;
subL->_bf = 0;
subLR->_bf = 0;
}
else if (bf == 1)
{
parent->_bf = 0;
subL->_bf = -1;
subLR->_bf = 0;
}
else if (bf == -1)
{
parent->_bf = 1;
subL->_bf = 0;
subLR->_bf = 0;
}
else
{
// subLR->_bf旋转前就有问题
assert(false);
}
}
void RotateRL(Node* parent)
{
Node* subR = parent->_right;
Node* subRL = subR->_left;
int bf = subRL->_bf;
RotateR(parent->_right);
RotateL(parent);
if (bf == 0)
{
subRL->_bf = 0;
parent->_bf = 0;
subR->_bf = 0;
}
else if (bf == 1)
{
subRL->_bf = 0;
parent->_bf = -1;
subR->_bf = 0;
}
else if (bf == -1)
{
subRL->_bf = 0;
parent->_bf = 0;
subR->_bf = 1;
}
else
{
// subLR->_bf旋转前就有问题
assert(false);
}
}
private:
Node* _root = nullptr;
};
1.6.AVL树的验证
AVL树是在二叉搜索树的基础上加入了平衡性的限制,因此要验证AVL树,可以分两步:1. 验证其为二叉搜索树如果中序遍历可得到一个有序的序列,就说明为二叉搜索树2. 验证其为平衡树每个节点子树高度差的绝对值不超过1(注意节点中如果没有平衡因子)节点的平衡因子是否计算正确AVL树的验证代码:AVLtree.h文件:#pragma once #include <assert.h> #include <vector> #include <queue> #include <time.h> template<class K, class V> struct AVLTreeNode { pair<K, V> _kv; AVLTreeNode<K, V>* _left; AVLTreeNode<K, V>* _right; AVLTreeNode<K, V>* _parent; // 右子树-左子树的高度差 int _bf; // balance factor AVLTreeNode(const pair<K, V>& kv) :_kv(kv) , _left(nullptr) , _right(nullptr) , _parent(nullptr) , _bf(0) {} // AVL树并没有规定必须要设计平衡因子 // 只是一个实现的选择,方便控制平衡 }; template<class K, class V> class AVLTree { typedef AVLTreeNode<K, V> Node; public: bool Insert(const pair<K, V>& kv) { // 1、搜索树的规则插入 // 2、看是否违反平衡规则,如果违反就需要处理:旋转 if (_root == nullptr) { _root = new Node(kv); _root->_bf = 0; 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); if (parent->_kv.first < kv.first) { parent->_right = cur; } else { parent->_left = cur; } cur->_parent = parent; // ... // 更新平衡因子 while (parent) // 最远要更新根 { if (cur == parent->_right) { parent->_bf++; } else { parent->_bf--; } // 是否继续更新? if (parent->_bf == 0) // 1 or -1 -》 0 插入节点填上矮的那边 { // 高度不变,更新结束 break; } else if (parent->_bf == 1 || parent->_bf == -1) // 0 -》 1 或 -1 插入节点导致一边变高了 { // 子树的高度变了,继续更新祖先 cur = cur->_parent; parent = parent->_parent; } else if (parent->_bf == 2 || parent->_bf == -2) // -1 or 1 -》 2 或 -2 插入节点导致本来高一边又变高了 { // 子树不平衡 -- 需要旋转处理 if (parent->_bf == 2 && cur->_bf == 1) // 左单旋 { RotateL(parent); } else if (parent->_bf == -2 && cur->_bf == -1) // 右单旋 { RotateR(parent); } else if (parent->_bf == -2 && cur->_bf == 1) // 左右双旋 { RotateLR(parent); } else if (parent->_bf == 2 && cur->_bf == -1) // 右左双旋 { RotateRL(parent); } break; } else { // 插入之前AVL就存在不平衡子树,|平衡因子| >= 2的节点 assert(false); } } return true; } private: 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; _root->_parent = nullptr; } else { if (parent == ppNode->_left) { ppNode->_left = subR; } else { ppNode->_right = subR; } subR->_parent = ppNode; } // 更新平衡因子 parent->_bf = 0; subR->_bf = 0; } 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; _root->_parent = nullptr; } else { if (ppNode->_left == parent) { ppNode->_left = subL; } else { ppNode->_right = subL; } subL->_parent = ppNode; } subL->_bf = parent->_bf = 0; } void RotateLR(Node* parent) { Node* subL = parent->_left; Node* subLR = subL->_right; int bf = subLR->_bf; RotateL(parent->_left); RotateR(parent); // 更新平衡因子 if (bf == 0) { parent->_bf = 0; subL->_bf = 0; subLR->_bf = 0; } else if (bf == 1) { parent->_bf = 0; subL->_bf = -1; subLR->_bf = 0; } else if (bf == -1) { parent->_bf = 1; subL->_bf = 0; subLR->_bf = 0; } else { // subLR->_bf旋转前就有问题 assert(false); } } void RotateRL(Node* parent) { Node* subR = parent->_right; Node* subRL = subR->_left; int bf = subRL->_bf; RotateR(parent->_right); RotateL(parent); if (bf == 0) { subRL->_bf = 0; parent->_bf = 0; subR->_bf = 0; } else if (bf == 1) { subRL->_bf = 0; parent->_bf = -1; subR->_bf = 0; } else if (bf == -1) { subRL->_bf = 0; parent->_bf = 0; subR->_bf = 1; } else { // subLR->_bf旋转前就有问题 assert(false); } } void _InOrder(Node* root) { if (root == nullptr) return; _InOrder(root->_left); cout << root->_kv.first << " "; _InOrder(root->_right); } int _Height(Node* root) { if (root == nullptr) return 0; int lh = _Height(root->_left); int rh = _Height(root->_right); return lh > rh ? lh + 1 : rh + 1; } bool _IsBalanceTree(Node* root) { // 空树也是AVL树 if (nullptr == root) return true; // 计算pRoot节点的平衡因子:即pRoot左右子树的高度差 int leftHeight = _Height(root->_left); int rightHeight = _Height(root->_right); int diff = rightHeight - leftHeight; // 如果计算出的平衡因子与pRoot的平衡因子不相等,或者 // pRoot平衡因子的绝对值超过1,则一定不是AVL树 if (abs(diff) >= 2) { cout << root->_kv.first << "节点平衡因子异常" << endl; return false; } if (diff != root->_bf) { cout << root->_kv.first << "节点平衡因子不符合实际" << endl; return false; } // pRoot的左和右如果都是AVL树,则该树一定是AVL树 return _IsBalanceTree(root->_left) && _IsBalanceTree(root->_right); } public: void InOrder() { _InOrder(_root); cout << endl; } //前面做题写过的层序遍历代码 vector<vector<int>> levelOrder() { vector<vector<int>> vv; if (_root == nullptr) return vv; queue<Node*> q; int levelSize = 1; q.push(_root); while (!q.empty()) { // levelSize控制一层一层出 vector<int> levelV; while (levelSize--) { Node* front = q.front(); q.pop(); levelV.push_back(front->_kv.first); if (front->_left) q.push(front->_left); if (front->_right) q.push(front->_right); } vv.push_back(levelV); for (auto e : levelV) { cout << e << " "; } cout << endl; // 上一层出完,下一层就都进队列 levelSize = q.size(); } return vv; } bool IsBalanceTree() { return _IsBalanceTree(_root); } int Height() { return _Height(_root); } private: Node* _root = nullptr; }; void TestAVLTree() { const size_t N = 10; vector<int> v; v.reserve(N); srand(time(0)); for (size_t i = 0; i < N; ++i) { v.push_back(rand()); } AVLTree<int, int> t; for (auto e : v) { t.Insert(make_pair(e, e)); } cout << "得到的随机树的形状:" << endl; t.levelOrder(); cout << endl; cout << "验证得到的随机树为二叉搜索树:" << endl; t.InOrder(); cout << endl; cout << "验证得到的随机树为平衡树:" << endl; cout << "是否平衡?" << t.IsBalanceTree() << endl; }
test.h文件:
#define _CRT_SECURE_NO_WARNINGS 1 #include <iostream> #include <set> #include <map> #include <string> using namespace std; #include "AVLTree.h" int main() { TestAVLTree(); return 0; }
1.7.AVL树的删除(了解)
因为AVL树也是二叉搜索树,可按照二叉搜索树的方式将节点删除,然后再更新平衡因子,只不过与删除不同的是删除节点后的平衡因子更新,最差情况下一直要调整到根节点的位置,AVL删除的步骤如下:第一步:按搜索树的规则删除第二步:更新平衡因子第三步:出现不平衡,旋转操作AVL树的删除不需要掌握,感兴趣可以去了解,具体实现学生们可参考《算法导论》或《数据结构-用面向对象方法与C++描述》殷人昆版。
1.8.AVL树的性能
AVL树是一棵绝对平衡的二叉搜索树,其要求每个节点的左右子树高度差的绝对值都不超过1,这样可以保证查询时高效的时间复杂度,即 。但是如果要对AVL树做一些结构修改的操作,性能非常低下,比如:插入时要维护其绝对平衡,旋转的次数比较多,更差的是在删除时,有可能一直要让旋转持续到根的位置。因此:如果需要一种查询高效且有序的数据结构,而且数据的个数为静态的(即不会改变),可以考虑AVL树,但一个结构经常修改,就不太适合。
2.红黑树
2.1.红黑树的概念
红黑树,是一种二叉搜索树,但在 每个结点上增加一个存储位表示结点的颜色,可以是Red或Black。 通过对任何一条从根到叶子的路径上各个结点着色方式的限制, 红黑树确保没有一条路径会比其他路径长出俩倍,因而是接近平衡的。注:
1.红黑树的最长路径不超过最短路径的2倍
2.对于二叉树的搜索来说,AVL树接近满二叉树搜索效率比红黑树高,例如一百万个数据,AVL树高度大概在20左右,红黑树高度有可能到了40行左右,但是搜索20次和搜索40次,对于CPU来说区别不大。对于二叉树的插入来说,相同插入数据,红黑树高度一般大于AVL树,红黑树的旋转次数则少于AVL树,因此红黑树的插入效率更高,在实际中,红黑树用的更多。
2.2.红黑树的性质
1. 每个结点不是红色就是黑色2. 根节点是黑色的3. 如果一个节点是红色的,则它的两个孩子结点是黑色的(没有连续的红色节点)4. 对于每个结点,从该结点到其所有后代叶结点的简单路径上,均包含相同数目的黑色结点 (每条路径都包含相同数量黑色结点)5. 每个叶子结点都是黑色的(此处的叶子结点指的是NIL空结点)思考:为什么满足上面的性质,红黑树就能保证:其最长路径中节点个数不会超过最短路径节点个数的两倍?答:有了上面的规则,那么一棵树的最短路径就是全黑结点,最长路径就是一黑一红结点间隔,又规定每条路径都包含相同数量黑色结点,那么最长路径就是最短路径的两倍。
2.3.红黑树节点的定义
红黑树结点的定义:
enum Colour { 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; Colour _col; RBTreeNode(const pair<K, V>& kv) :_kv(kv) , _left(nullptr) , _right(nullptr) , _parent(nullptr) , _col(RED) {} };
思考:在节点的定义中,为什么要将节点的默认颜色给成红色的?答:插入一个新结点,插入结点的颜色默认设置成红色,因为新增节点是红色,可能破坏上面的规则3(没有连续的红色节点),新增结点是黑色,一定破坏上面的规则4(每条路径都包含相同数量黑色结点),规则4很难维护(破坏规则3只影响父节点和子节点两个结点,破坏规则4很多结点颜色需要跟着改),因此选择插入红色,影响范围小。
2.4.红黑树结构
为了后续实现关联式容器简单,红黑树的实现中增加一个头结点,因为跟节点必须为黑色,为了与根节点进行区分,将头结点给成黑色,并且让头结点的pParent指向红黑树的根节点,pLeft指向红黑树中最小的节点,_pRight指向红黑树中最大的节点,如下:
2.5.红黑树的插入操作
红黑树就是在二叉搜索树的基础上引入了colour,因此红黑树也可以看成是二叉搜索树。那么红黑树的插入过程可以分为两步:1. 按照二叉搜索树的方式插入新节点2. 检测新节点插入后,红黑树的性质是否造到破坏
具体地说:
1.插入一个新结点,插入新结点的颜色设置成红色,因为前面我们提到新节点给成红色影响小。2.因为新节点的默认颜色是红色,因此:如果其双亲节点的颜色是黑色,没有违反红黑树任何性质,则不需要调整;但当新插入节点的双亲节点颜色为红色时,就违反了性质三不能有连在一起的红色节点,此时需要对红黑树分以下三种情况来讨论:约定:cur为当前节点,p为父节点,g为祖父节点,u为叔叔节点,其中,p一定是红色,g一定是黑色,u的颜色不确定。
情况一: cur为红,p为红,g为黑,u存在且为红解决方式:将p和u改成黑,将g改为红,然后把g当成cur,继续向上调整注:
1.这里将g变红的理由是,这棵树有可能是局部子树,将g变红可以保持新节点插入前后子树每条路径上黑色结点的数量不变,如下图所示,这样插入新节点并且修改完后该子树一定还是红黑树。2.只要符合cur为红,p为红,g为黑,u存在且为红那就是第一种情况,不关心p和u得左右位置,也不关心当前结点cur是p得左节点还是右节点,如下图一、二、三所示都符合情况一,因为情况一只变色不旋转。
情况二: cur为红,p为红,g为黑,u不存在/u存在且为黑(其中p为g的左孩子,cur为p的左孩子或者p为g的右孩子,cur为p的右孩子 )解决方式:先右旋或左旋,然后将g变红p变黑。注:
1.这里经过旋转+变色后,可以保持新节点插入前后子树每条路径上黑色结点的数量不变,如下图所示,这样插入新节点并且修改完后该子树一定还是红黑树。2.满足cur为红,p为红,g为黑,u不存在/u存在且为黑,如果p为g的左孩子,cur为p的左孩子,则进行右单旋转和变色;如果p为g的右孩子,cur为p的右孩子,则进行左单旋转和变色。只有p为g的左孩子,cur为p的左孩子或者p为g的右孩子,cur为p的右孩子,才符合情况二的条件。
情况三: cur为红,p为红,g为黑,u不存在/u存在且为黑(其中p为g的左孩子,cur为p的右孩子或者p为g的右孩子,cur为p的左孩子)
解决方式:先左右旋或右左旋,然后将g变红cur变黑。
注:
1.这里经过旋转+变色后,可以保持新节点插入前后子树每条路径上黑色结点的数量不变,如下图所示,这样插入新节点并且修改完后该子树一定还是红黑树。2.满足cur为红,p为红,g为黑,u不存在/u存在且为黑,如果p为g的左孩子,cur为p的右孩子,则进行左右双旋转和变色;如果p为g的右孩子,cur为p的左孩子,则进行右左双旋转和变色。只有p为g的左孩子,cur为p的右孩子或者p为g的右孩子,cur为p的左孩子,才符合情况三的条件。
2.6.红黑树插入和旋转代码实现
BRTree.h文件:
#pragma once
enum Colour
{
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;
Colour _col;
RBTreeNode(const pair<K, V>& kv)
:_kv(kv)
, _left(nullptr)
, _right(nullptr)
, _parent(nullptr)
, _col(RED)
{}
};
template<class K, class V>
struct RBTree
{
typedef RBTreeNode<K, V> Node;
public:
bool Insert(const pair<K, V>& kv)
{
// 1、搜索树的规则插入
// 2、看是否违反平衡规则,如果违反就需要处理:旋转
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;
}
else
{
parent->_left = cur;
}
cur->_parent = parent;
// 存在连续红色节点
while (parent && parent->_col == RED)
{
Node* grandfater = parent->_parent;
assert(grandfater);
if (grandfater->_left == parent)
{
Node* uncle = grandfater->_right;
// 情况一:
if (uncle && uncle->_col == RED) // 叔叔存在且为红
{
// 变色
parent->_col = uncle->_col = BLACK;
grandfater->_col = RED;
// 继续往上处理
cur = grandfater;
parent = cur->_parent;
}
else // 叔叔不存在 或者 叔叔存在且为黑
{
if (cur == parent->_left) // 单旋
{
// g
// p
// c
RotateR(grandfater);
parent->_col = BLACK;
grandfater->_col = RED;
}
else // 双旋
{
// g
// p
// c
RotateL(parent);
RotateR(grandfater);
cur->_col = BLACK;
grandfater->_col = RED;
}
break;
}
}
else //(grandfater->_right == parent)
{
Node* uncle = grandfater->_left;
// 情况一:
if (uncle && uncle->_col == RED)
{
// 变色
parent->_col = uncle->_col = BLACK;
grandfater->_col = RED;
// 继续往上处理
cur = grandfater;
parent = cur->_parent;
}
else
{
if (cur == parent->_right)
{
// g
// p
// c
RotateL(grandfater);
parent->_col = BLACK;
grandfater->_col = RED;
}
else // 双旋
{
// g
// p
// c
RotateR(parent);
RotateL(grandfater);
cur->_col = BLACK;
grandfater->_col = RED;
}
break;
}
}
}
_root->_col = BLACK;
return true;
}
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;
_root->_parent = nullptr;
}
else
{
if (parent == ppNode->_left)
{
ppNode->_left = subR;
}
else
{
ppNode->_right = subR;
}
subR->_parent = ppNode;
}
}
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;
_root->_parent = nullptr;
}
else
{
if (ppNode->_left == parent)
{
ppNode->_left = subL;
}
else
{
ppNode->_right = subL;
}
subL->_parent = ppNode;
}
}
private:
Node* _root = nullptr;
};
2.7.红黑树的验证
红黑树的检测分为两步:1. 检测其是否满足二叉搜索树(中序遍历是否为有序序列)2. 检测其是否满足红黑树的性质红黑树的验证代码:RBTree.h文件:#pragma once enum Colour { 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; Colour _col; RBTreeNode(const pair<K, V>& kv) :_kv(kv) , _left(nullptr) , _right(nullptr) , _parent(nullptr) , _col(RED) {} }; template<class K, class V> struct RBTree { typedef RBTreeNode<K, V> Node; public: bool Insert(const pair<K, V>& kv) { // 1、搜索树的规则插入 // 2、看是否违反平衡规则,如果违反就需要处理:旋转 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; } else { parent->_left = cur; } cur->_parent = parent; // 存在连续红色节点 while (parent && parent->_col == RED) { Node* grandfater = parent->_parent; assert(grandfater); if (grandfater->_left == parent) { Node* uncle = grandfater->_right; // 情况一: if (uncle && uncle->_col == RED) // 叔叔存在且为红 { // 变色 parent->_col = uncle->_col = BLACK; grandfater->_col = RED; // 继续往上处理 cur = grandfater; parent = cur->_parent; } else // 叔叔不存在 或者 叔叔存在且为黑 { if (cur == parent->_left) // 单旋 { // g // p // c RotateR(grandfater); parent->_col = BLACK; grandfater->_col = RED; } else // 双旋 { // g // p // c RotateL(parent); RotateR(grandfater); cur->_col = BLACK; grandfater->_col = RED; } break; } } else //(grandfater->_right == parent) { Node* uncle = grandfater->_left; // 情况一: if (uncle && uncle->_col == RED) { // 变色 parent->_col = uncle->_col = BLACK; grandfater->_col = RED; // 继续往上处理 cur = grandfater; parent = cur->_parent; } else { if (cur == parent->_right) { // g // p // c RotateL(grandfater); parent->_col = BLACK; grandfater->_col = RED; } else // 双旋 { // g // p // c RotateR(parent); RotateL(grandfater); cur->_col = BLACK; grandfater->_col = RED; } break; } } } _root->_col = BLACK; return true; } vector<vector<int>> levelOrder() { vector<vector<int>> vv; if (_root == nullptr) return vv; queue<Node*> q; int levelSize = 1; q.push(_root); while (!q.empty()) { // levelSize控制一层一层出 vector<int> levelV; while (levelSize--) { Node* front = q.front(); q.pop(); levelV.push_back(front->_kv.first); if (front->_left) q.push(front->_left); if (front->_right) q.push(front->_right); } vv.push_back(levelV); for (auto e : levelV) { cout << e << " "; } cout << endl; // 上一层出完,下一层就都进队列 levelSize = q.size(); } return vv; } 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; _root->_parent = nullptr; } else { if (parent == ppNode->_left) { ppNode->_left = subR; } else { ppNode->_right = subR; } subR->_parent = ppNode; } } 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; _root->_parent = nullptr; } else { if (ppNode->_left == parent) { ppNode->_left = subL; } else { ppNode->_right = subL; } subL->_parent = ppNode; } } int _maxHeight(Node* root) { if (root == nullptr) return 0; int lh = _maxHeight(root->_left); int rh = _maxHeight(root->_right); return lh > rh ? lh + 1 : rh + 1; } int _minHeight(Node* root) { if (root == nullptr) return 0; int lh = _minHeight(root->_left); int rh = _minHeight(root->_right); return lh < rh ? lh + 1 : rh + 1; } void _InOrder(Node* root) { if (root == nullptr) return; _InOrder(root->_left); cout << root->_kv.first << " "; _InOrder(root->_right); } bool _IsValidRBTree(Node* pRoot, size_t k, const size_t blackCount) { //走到null之后,判断k和black是否相等 if (nullptr == pRoot) { if (k != blackCount) { cout << "违反性质四:每条路径中黑色节点的个数必须相同" << endl; return false; } return true; } // 统计黑色节点的个数 if (BLACK == pRoot->_col) k++; // 检测当前节点与其双亲是否都为红色 if (RED == pRoot->_col && pRoot->_parent && pRoot->_parent->_col == RED) { cout << "违反性质三:存在连在一起的红色节点" << endl; return false; } return _IsValidRBTree(pRoot->_left, k, blackCount) && _IsValidRBTree(pRoot->_right, k, blackCount); } public: void InOrder() { _InOrder(_root); cout << endl; } void Height() { cout << "最长路径:" << _maxHeight(_root) << endl; cout << "最短路径:" << _minHeight(_root) << endl; } bool IsBalanceTree() { // 检查红黑树几条规则 Node* pRoot = _root; // 空树也是红黑树 if (nullptr == pRoot) return true; // 检测根节点是否满足情况 if (BLACK != pRoot->_col) { cout << "违反红黑树性质二:根节点必须为黑色" << endl; return false; } // 获取任意一条路径中黑色节点的个数 -- 比较基准值 size_t blackCount = 0; Node* pCur = pRoot; while (pCur) { if (BLACK == pCur->_col) blackCount++; pCur = pCur->_left; } // 检测是否满足红黑树的性质,k用来记录路径中黑色节点的个数 size_t k = 0; return _IsValidRBTree(pRoot, k, blackCount); } private: Node* _root = nullptr; }; void TestRBTree() { const size_t N = 10; vector<int> v; v.reserve(N); srand(time(0)); for (size_t i = 0; i < N; ++i) { v.push_back(rand()); } RBTree<int, int> t; for (auto e : v) { t.Insert(make_pair(e, e)); } cout << "得到的随机树的形状:" << endl; t.levelOrder(); cout << endl; cout << "验证得到的随机树为二叉搜索树:" << endl; t.InOrder(); cout << endl; cout << "验证得到的随机树为平衡树:" << endl; cout << "是否平衡?" << t.IsBalanceTree() << endl; cout << endl; cout << "得到的随机树最长最短路径:" << endl; t.Height(); }
test.cpp文件:
#define _CRT_SECURE_NO_WARNINGS 1 #include <iostream> #include <set> #include <map> #include <string> #include <vector> #include <queue> #include <assert.h> using namespace std; #include "RBTree.h" int main() { TestRBTree(); return 0; }
2.8.红黑树的删除
红黑树的删除本节不做讲解,有兴趣的同学可参考:《算法导论》或者《STL源码剖析》
2.9.红黑树与AVL树的比较
红黑树和AVL树都是高效的平衡二叉树,增删改查的时间复杂度都是 ,红黑树不追求绝对平衡,其只需保证最长路径不超过最短路径的2倍,相对而言,降低了插入和旋转的次数,所以在经常进行增删的结构中性能比AVL树更优,而且红黑树实现比较简单,所以实际运用中红黑树更多。
2.10.红黑树的应用
1. C++ STL库 -- map/set、mutil_map/mutil_set2. Java 库3. linux内核4. 其他一些库
3.红黑树模拟实现STL中的map与set
3.1.封装红黑树代码,同时实现map和set
将红黑树RBTree进行封装,使之可以同时实现map和set
源码剖析:
上图是set和map创建红黑树的部分代码,可以看出set中将Key分别类型重定义成key_type和value_type,创建红黑树rb_tree的时候将key_type和value_type作为rb_tree的第一二个模板参数进行传递;map中将Key类型重定义成key_type,将pair<const Key, T>类型重定义成value_type,创建红黑树rb_tree的时候将key_type和value_type作为rb_tree的第一二个模板参数进行传递。红黑树rb_tree的代码如下图所示
红黑树部分代码如上图所示,可以看出set相当于将K传给红黑树rb_tree的第二个模板参数Value,map相当于将pair<K,V>传给红黑树rb_tree的第二个模板参数Value,那么使用红黑树rb_tree的第二个模板参数Value就可以用来创建set或map中对应的数据。红黑树rb_tree中将Value传给红黑树节点__rb_tree_node结构体,__rb_tree_node结构体里面使用value类型创建变量来存储对应set或map数据,在红黑树rb_tree中将创建节点的__rb_tree_node结构体类型重定义成rb_tree_node。那么使用红黑树rb_tree的第二个模板参数Value就可以控制实现set或map,传rb_tree的第一个模板参数Key有什么意义呢?
红黑树rb_tree中至少要有查找find接口,find接口声明为iterator find(const Key& key),要借助rb_tree第一个模板参数Key类型来查找数据。
下面是初步改进RBTree,使之同时实现map和set。
解决Insert插入函数中set和map数据比较的问题:
在插入Insert接口中,其形参data是T类型的,set时T类型是K,map时T类型是pair<K,V>,Insert接口里面对K比较大小是可以的,但是能否对pair<K,V>比较大小呢?pair类中重载的比较大小函数是否是我们想要的呢?
pair类的比较大小重载函数声明如下图一所示,比较规则如下图二所示。其比较规则为first小则小,当first不小的时候second小则小,这里的比较规则不是我们想要的,我们想要的是只对key比较,不对value比较。那我们应该如何解决这里pair类比较的问题呢?
红黑树RBTree中我们不知道Insert插入函数形参data的类型T是K还是pair<K,V>,如果是K的话可以直接进行比较,如果是pair<K,V>的话应该取其first进行比较。我们给红黑树RBTree的模板中加一个仿函数类KeyOfT作为第三个模板参数,在map和set中定义自己的仿函数类MapKeyOfT和SetKeyOfT进行比较工作,然后将仿函数类传给红黑树RBTree的第三个模板参数,红黑树中使用仿函数类KeyOfT定义一个仿函数kot,直接利用仿函数kot来进行比较工作,如下图所示
3.2.红黑树的迭代器
库里面实现set和map的红黑树中增加了一个哨兵位的头节点header,header的left指向了最左节点(key值最小的节点),header的right指向了最右节点(key值最大的节点),header的parent指向根节点,根节点的parent指向header,如下图所示。
红黑树中begin函数返回首节点的迭代器,该迭代器指向的节点就是header的left指向的最左节点,红黑树中end函数返回尾节点下一个节点的迭代器,该迭代器指向的节点就是哨兵位的头节点header(迭代器的左闭右开)。
我们将该模型简化一下,不使用哨兵位的头节点header。
红黑树中begin函数返回节点的迭代器,该迭代器指向的节点是树的最左节点,我们从根节点root一直往左找,找到的最后一个非空节点就是树的最左节点。红黑树中end函数返回尾节点下一个节点的迭代器,我们使用空指针构造的迭代器作为尾节点下一个节点的迭代器,end函数返回该空指针构造的迭代器。
set和map中将红黑树的迭代器类型重定义成iterator作为自己的迭代器,set和map里面的begin函数和end函数也直接调用红黑树中的begin函数和end函数即可。
set类代码:
#pragma once #include "RBTree.h" namespace bit { template<class K> class set { struct SetKeyOfT { const K& operator()(const K& key) { return key; } }; public: typedef typename RBTree<K, K, SetKeyOfT>::const_iterator iterator; typedef typename RBTree<K, K, SetKeyOfT>::const_iterator const_iterator; iterator begin() const { return _t.Begin(); } iterator end() const { return _t.End(); } pair<iterator, bool> insert(const K& key) { //pair<typename RBTree<K, K, SetKeyOfT>::iterator, bool> ret = _t.Insert(key); auto ret = _t.Insert(key); return pair<iterator, bool>(iterator(ret.first._node), ret.second); } iterator find(const K& key) { return _t.Find(key); } private: RBTree<K, K, SetKeyOfT> _t; }; }
map类代码:
#pragma once #include "RBTree.h" namespace bit { template<class K, class V> class map { struct MapKeyOfT { const K& operator()(const pair<K, V>& kv) { return kv.first; } }; public: typedef typename RBTree<K, pair<K, V>, MapKeyOfT>::iterator iterator; typedef typename RBTree<K, pair<K, V>, MapKeyOfT>::const_iterator const_iterator; iterator begin() { return _t.Begin(); } iterator end() { return _t.End(); } pair<iterator, bool> insert(const pair<K, V>& kv) { return _t.Insert(kv); } iterator find(const K& key) { return _t.Find(key); } V& operator[](const K& key) { pair<iterator, bool> ret = insert(make_pair(key, V())); return ret.first->second; } private: RBTree<K, pair<K, V>, MapKeyOfT> _t; }; }
红黑树迭代器部分代码:
template<class T, class Ref, class Ptr> struct __RBTreeIterator { typedef RBTreeNode<T> Node; typedef __RBTreeIterator<T, Ref, Ptr> Self; Node* _node; __RBTreeIterator(Node* node) :_node(node) {} Ref operator*() { return _node->_data; } Ptr operator->() { return &_node->_data; } Self& operator++() { if (_node->_right == nullptr) { // 找祖先里面,孩子是父亲左的那个 Node* cur = _node; Node* parent = cur->_parent; while (parent && parent->_right == cur) { cur = cur->_parent; parent = parent->_parent; } _node = parent; } else { // 右子树的最左节点 Node* subLeft = _node->_right; while (subLeft->_left) { subLeft = subLeft->_left; } _node = subLeft; } return *this; } Self operator++(int) { Self tmp(*this); ++(*this); return tmp; } Self& operator--() { if (_node->_left == nullptr) { // 找祖先里面,孩子是父亲 Node* cur = _node; Node* parent = cur->_parent; while (parent && cur == parent->_left) { cur = cur->_parent; parent = parent->_parent; } _node = parent; } else { // 左子树的最右节点 Node* subRight = _node->_left; while (subRight->_right) { subRight = subRight->_right; } _node = subRight; } return *this; } Self operator--(int) { Self tmp(*this); --(*this); return tmp; } bool operator!=(const Self& s) const { return _node != s._node; } bool operator==(const Self& s) const { return _node == s->_node; } };
注:
1.set和map中将红黑树的迭代器类型重定义成iterator作为自己的迭代器的代码应该用typename修饰,如下图所示。RBTree<K,K,SetKeyOfT>是一个类模板,取类模板中的内嵌类型iterator和const_iterator进行类型重定义,因为类模板RBTree<K,K,SetKeyOfT>没有实例化,编译器无法辨认RBTree<K,K,SetKeyOfT>::iterator和RBTree<K,K,SetKeyOfT>::const_iterator是什么,加上typename修饰告诉编译器这是一个类型,等类模板实例化了再去取里面的内嵌类型iterator和const_iterator。
还有一种解释是RBTree<K,K,SetKeyOfT>::iterator和RBTree<K,K,SetKeyOfT>::const_iterator是去访问类RBTree<K,K,SetKeyOfT>中的内容iterator和const_iterator,系统无法辨认要访问的内容是静态的变量还是类的内嵌类型,加上typename修饰告诉编译器要访问的是类的内嵌类型。
2.实现operator++运算符重载函数,使迭代器按照中序遍历的顺序指向下一个节点。operator++运算符重载函数的算法思路为:
根据上面的算法,当迭代器走到树的最右边节点也就是最后一个节点之后,右子树为空找找孩子是祖先左的那个祖先节点,一直找到了根节点的parent,根节点的parent为空,我们前面定义的end函数返回空指针构造的迭代器,二者正好符合。
前置++的operator++()运算符重载函数如下图一所示,后置++的operator++(int)运算符重载函数复用前置++代码如下图二所示
3.实现operator--运算符重载函数,使迭代器按照中序遍历的顺序指向上一个节点。operator--运算符重载函数的算法思路为:
前置--的operator--()运算符重载函数如下图一所示,后置--的operator--(int)运算符重载函数复用前置--代码如下图二所示
4.set里面的key值不能被修改,所以set里面的iterator迭代器也不能进行修改操作,所以我们应该将set里面的iterator迭代器用红黑树中的const_iterator类型重定义,如下图所示
但是set类的begin函数中调用的是红黑树的Begin函数,红黑树的Begin函数返回的是iterator普通迭代器,而set类的begin函数返回类型虽然也是iterator,但在set中我们将const_iterator类型重定义成iterator,因此set类的begin函数返回类型其实是const修饰的迭代器,这里类型不匹配会报错。
下图一所示是set类源代码中的begin和end函数,源代码中begin和end函数都使用const修饰,这样即使是普通的红黑树变量t,由于自动经过const修饰,调用的也是红黑树中const修饰的begin和end函数,红黑树中const修饰的begin和end函数返回的是const_iterator类型的迭代器,类型匹配。改进后的代码如下图二所示。
5.map类中的operator[ ]运算符重载函数的功能是返回key对应的value,前面我们讲过operator[ ]运算符重载函数是借助于insert函数来实现的。库中insert函数如果插入成功,则返回一个pair类型对象,pair中first为新插入节点的迭代器second为true;库中insert函数如果插入失败,则返回一个pair类型对象,pair中first为已经有的key节点的迭代器second为false,所以这里我们需要将红黑树中之前写的insert函数的返回值部分进行修改,然后将set和map中insert函数返回值跟着修改,改完之后map类中的operator[ ]运算符重载函数复用红黑树的insert函数来实现。map类中的operator[ ]运算符重载函数实现代码如下图所示。
如下图一所示,这里set的insert函数中返回的pair<iterator,bool>中iterator是红黑树中的const_iterator,而红黑树的Insert函数返回的pair<iterator,bool>中iterator就是普通迭代器,这里类型不匹配,我们需要在set的insert函数中进行一层转换,如下图二所示。
3.3.红黑树模拟实现STL中map与set的代码
Set.h文件:
#pragma once
#include "RBTree.h"
namespace bit
{
template<class K>
class set
{
struct SetKeyOfT
{
const K& operator()(const K& key)
{
return key;
}
};
public:
typedef typename RBTree<K, K, SetKeyOfT>::const_iterator iterator;
typedef typename RBTree<K, K, SetKeyOfT>::const_iterator const_iterator;
iterator begin() const
{
return _t.Begin();
}
iterator end() const
{
return _t.End();
}
pair<iterator, bool> insert(const K& key)
{
//pair<typename RBTree<K, K, SetKeyOfT>::iterator, bool> ret = _t.Insert(key);
auto ret = _t.Insert(key);
return pair<iterator, bool>(iterator(ret.first._node), ret.second);
}
iterator find(const K& key)
{
return _t.Find(key);
}
private:
RBTree<K, K, SetKeyOfT> _t;
};
void test_set1()
{
set<int> s;
s.insert(8);
s.insert(6);
s.insert(11);
s.insert(5);
s.insert(6);
s.insert(7);
s.insert(10);
s.insert(13);
s.insert(12);
s.insert(15);
set<int>::iterator it = s.begin();
while (it != s.end())
{
cout << *it << " ";
++it;
}
cout << endl;
for (auto e : s)
{
cout << e << " ";
}
cout << endl;
}
}
Map.h文件:
#pragma once
#include "RBTree.h"
namespace bit
{
template<class K, class V>
class map
{
struct MapKeyOfT
{
const K& operator()(const pair<K, V>& kv)
{
return kv.first;
}
};
public:
typedef typename RBTree<K, pair<K, V>, MapKeyOfT>::iterator iterator;
typedef typename RBTree<K, pair<K, V>, MapKeyOfT>::const_iterator const_iterator;
iterator begin()
{
return _t.Begin();
}
iterator end()
{
return _t.End();
}
pair<iterator, bool> insert(const pair<K, V>& kv)
{
return _t.Insert(kv);
}
iterator find(const K& key)
{
return _t.Find(key);
}
V& operator[](const K& key)
{
pair<iterator, bool> ret = insert(make_pair(key, V()));
return ret.first->second;
}
private:
RBTree<K, pair<K, V>, MapKeyOfT> _t;
};
void test_map1()
{
map<string, int> m;
m.insert(make_pair("111", 1));
m.insert(make_pair("555", 5));
m.insert(make_pair("333", 3));
m.insert(make_pair("222", 2));
map<string, int>::iterator it = m.begin();
while (it != m.end())
{
cout << it->first << ":" << it->second << endl;
++it;
}
cout << endl;
for (auto& kv : m)
{
cout << kv.first << ":" << kv.second << endl;
}
cout << endl;
}
void test_map2()
{
string arr[] = { "苹果", "西瓜", "苹果", "西瓜", "苹果", "苹果", "西瓜", "苹果", "香蕉", "苹果" , "香蕉" };
map<string, int> countMap;
for (auto& str : arr)
{
countMap[str]++;
}
for (const auto& kv : countMap)
{
cout << kv.first << ":" << kv.second << endl;
}
}
void test_map3()
{
map<string, string> dict;
dict["insert"];
dict["insert"] = "";
dict["left"] = "";
}
}
RBTree.h文件:
#pragma once
enum Colour
{
RED,
BLACK,
};
template<class T>
struct RBTreeNode
{
RBTreeNode<T>* _left;
RBTreeNode<T>* _right;
RBTreeNode<T>* _parent;
T _data; // 数据
Colour _col;
RBTreeNode(const T& data)
:_data(data)
, _left(nullptr)
, _right(nullptr)
, _parent(nullptr)
, _col(RED)
{}
};
template<class T, class Ref, class Ptr>
struct __RBTreeIterator
{
typedef RBTreeNode<T> Node;
typedef __RBTreeIterator<T, Ref, Ptr> Self;
Node* _node;
__RBTreeIterator(Node* node)
:_node(node)
{}
Ref operator*()
{
return _node->_data;
}
Ptr operator->()
{
return &_node->_data;
}
Self& operator++()
{
if (_node->_right == nullptr)
{
// 找祖先里面,孩子是父亲左的那个
Node* cur = _node;
Node* parent = cur->_parent;
while (parent && parent->_right == cur)
{
cur = cur->_parent;
parent = parent->_parent;
}
_node = parent;
}
else
{
// 右子树的最左节点
Node* subLeft = _node->_right;
while (subLeft->_left)
{
subLeft = subLeft->_left;
}
_node = subLeft;
}
return *this;
}
Self operator++(int)
{
Self tmp(*this);
++(*this);
return tmp;
}
Self& operator--()
{
if (_node->_left == nullptr)
{
// 找祖先里面,孩子是父亲
Node* cur = _node;
Node* parent = cur->_parent;
while (parent && cur == parent->_left)
{
cur = cur->_parent;
parent = parent->_parent;
}
_node = parent;
}
else
{
// 左子树的最右节点
Node* subRight = _node->_left;
while (subRight->_right)
{
subRight = subRight->_right;
}
_node = subRight;
}
return *this;
}
Self operator--(int)
{
Self tmp(*this);
--(*this);
return tmp;
}
bool operator!=(const Self& s) const
{
return _node != s._node;
}
bool operator==(const Self& s) const
{
return _node == s->_node;
}
};
// T决定红黑树存什么数据
// set RBTree<K, K>
// map RBTree<K, pair<K, V>>
// KeyOfT -> 支持取出T对象中key的仿函数
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* subLeft = _root;
while (subLeft && subLeft->_left)
{
subLeft = subLeft->_left;
}
return iterator(subLeft);
}
iterator End()
{
return iterator(nullptr);
}
const_iterator Begin() const
{
Node* subLeft = _root;
while (subLeft && subLeft->_left)
{
subLeft = subLeft->_left;
}
return const_iterator(subLeft);
}
const_iterator End() const
{
return const_iterator(nullptr);
}
pair<iterator, bool> Insert(const T& data)
{
// 1、搜索树的规则插入
// 2、看是否违反平衡规则,如果违反就需要处理:旋转
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), true);
}
}
cur = new Node(data);
Node* newnode = cur;
cur->_col = RED;
if (kot(parent->_data) < kot(data))
{
parent->_right = cur;
}
else
{
parent->_left = cur;
}
cur->_parent = parent;
// 存在连续红色节点
while (parent && parent->_col == RED)
{
Node* grandfater = parent->_parent;
assert(grandfater);
if (grandfater->_left == parent)
{
Node* uncle = grandfater->_right;
// 情况一:
if (uncle && uncle->_col == RED) // 叔叔存在且为红
{
// 变色
parent->_col = uncle->_col = BLACK;
grandfater->_col = RED;
// 继续往上处理
cur = grandfater;
parent = cur->_parent;
}
else // 叔叔不存在 或者 叔叔存在且为黑
{
if (cur == parent->_left) // 单旋
{
// g
// p
// c
RotateR(grandfater);
parent->_col = BLACK;
grandfater->_col = RED;
}
else // 双旋
{
// g
// p
// c
RotateL(parent);
RotateR(grandfater);
cur->_col = BLACK;
grandfater->_col = RED;
}
break;
}
}
else //(grandfater->_right == parent)
{
Node* uncle = grandfater->_left;
// 情况一:
if (uncle && uncle->_col == RED)
{
// 变色
parent->_col = uncle->_col = BLACK;
grandfater->_col = RED;
// 继续往上处理
cur = grandfater;
parent = cur->_parent;
}
else
{
if (cur == parent->_right)
{
// g
// p
// c
RotateL(grandfater);
parent->_col = BLACK;
grandfater->_col = RED;
}
else // 双旋
{
// g
// p
// c
RotateR(parent);
RotateL(grandfater);
cur->_col = BLACK;
grandfater->_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;
Node* ppNode = parent->_parent;
subR->_left = parent;
parent->_parent = subR;
if (parent == _root)
{
_root = subR;
_root->_parent = nullptr;
}
else
{
if (parent == ppNode->_left)
{
ppNode->_left = subR;
}
else
{
ppNode->_right = subR;
}
subR->_parent = ppNode;
}
}
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;
_root->_parent = nullptr;
}
else
{
if (ppNode->_left == parent)
{
ppNode->_left = subL;
}
else
{
ppNode->_right = subL;
}
subL->_parent = ppNode;
}
}
iterator Find(const K& key)
{
Node* cur = _root;
KeyOfT kot;
while (cur)
{
if (kot(cur->_data) < key)
{
cur = cur->_right;
}
else if (kot(cur->_data) > key)
{
cur = cur->_left;
}
else
{
return iterator(cur);
}
}
return End();
}
private:
Node* _root = nullptr;
};
test.cpp文件:
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <set>
#include <map>
#include <string>
#include<assert.h>
using namespace std;
#include "RBTree.h"
#include "Map.h"
#include "Set.h"
int main()
{
//bit::test_map2();
bit::test_set1();
return 0;
}