• map和set


    目录

    关联式容器

    键值对

    set的简介

    map的简介

    AVL树的实现

    红黑树的实现

    红黑树封装map和set

    全部代码


    关联式容器

    关联式容器也是用来存储数据的,与序列式容器vector,list等等不同的是,它存储的是<Key,Value>的键值对,在数据检索时效率更高

    STL中分为两种,一种是树形结构,另一种则是哈希结构

    树型结构的关联式容器主要有四种:map、set、multimap、multiset,底层结构都是平衡搜索树(红黑树)

    键值对

    用来表示具有一一对应关系的一种结构,该结构中一般只包含两个成员变量key和value,key代表键值,value表示与key对应的信息,比如字典中的一个单词,则有与它相应的中文意思,单词可为键值Key,中文意思则为Value

    set的简介

    set具有排序+去重的作用,而multiset则只有排序的作用

    set中的元素的key即是value,即set只存放value,其底层存放的是<value,value>

    set中的元素不能在容器中修改(元素总是const),但可以插入或者删除

    在multiset容器中,用find函数查找的val有多个值时,返回中序第一个val值所在节点的迭代器

    set中插入元素时,只需要插入value即可,不需要构造键值对

    map的简介

    map具有排序+去重的作用,而multimap则只有排序的作用,所以map中的key是唯一的,multimap中的key是可以重复的

    map中存放的元素都是<key,value>键值对

    在map的内部,key与value通过成员类型value_type绑定在一起,为其取别名称为pair

    在内部,map中的元素总是按照键值key进行比较排序的

    map支持下标访问符,即在[]中放入key,就可以找到与key对应的value

    AVL树的实现

    AVL树的左右子树都是AVL树,它的左右子树高度差的绝对值不超过1,所以它也是高度平衡的,如果它有n个结点,其高度可保持在 log2 n,搜索时间复杂度O( log2 n)

    由于AVL树比较复杂,而且一般工作中不需要去实现,库里面有,所以只讲插入,简单了解它即可

    节点结构

    这里采用非递归的写法,以及三叉链的形式,借助平衡因子来维持平衡

    AVL树的私有成员及其构造函数,以及依然采用模板,泛型写法

    开始是空树时

    其余情况,先按照二叉搜索树的形式插入

     

    每次插入时调节每个节点的平衡因子

      

    当其中一个节点的平衡因子为2或-2时,则需要旋转来控制平衡

    由于实体图情况种类太多,所以采用抽象图的方法则只有4种旋转

    右单旋

     

    上述情况是要旋转的节点是根节点,所以最后代码如下图

    如果不是根节点则要些微改变,代码如下

     

    左单旋 

     上述情况是要旋转的节点是根节点,所以最后代码如下图

    如果不是根节点则要些微改变,代码如下

    左右双旋

    这里左右双旋只调用左旋转和右旋转还不行,还需单独调整它的平衡因子,因为左单旋或者右单选调节的平衡因子,在左右双旋不一定正确 

    如何调整正确每个节点的平衡因子,主要看上图中第二个图形subLR的平衡因子,所以先保存其平衡因子

    然后就有下列几种情况,走到else则表示前面的插入早就出问题了

    右左双旋

     

    这里右左双旋只调用右旋转和左旋转还不行,还需单独调整它的平衡因子,因为右单旋或者左单选调节的平衡因子,在右左双旋不一定正确 

    如何调整正确每个节点的平衡因子,主要看上图中第二个图形subRL的平衡因子,所以先保存其平衡因子

    然后就有下列几种情况,走到else则表示前面的插入早就出问题了

    验证是否是AVL树

    一个是检验它是否是二叉搜索树,另一个则是检验它是否平衡,验证它是二叉搜索树,只需要写出它的中序遍历,看其是否有序即可

    检验AVL树是否平衡

    首先如果这颗树为空树就直接返回true

    通过每个节点左右子树的高度来检查,首先先算出高度

    然后通过该节点左右子树的高度差的绝对值与平衡因子的比较,来确定是否平衡,不平衡就返回false

    最后就是层层递归下去,把每个节点都遍历一遍,看是否符合平衡

    AVL树的性能

    查询时,效率非常高,时间复杂度为log2 n,但要对AVL树做一些结构修改的操作,性能非常低,比如:插入时要维护平衡,旋转的次数就会非常多,所以工作中用红黑树用的比较多

    红黑树的实现

    概念

    红黑树,是一种二叉搜索树,但在每个结点上增加一个存储位表示结点的颜色,可以是Red或Black,所以这里可以用到枚举

    通过对任何一条从根到叶子的路径上各个结点着色方式的限制,红黑树确保没有一条路径会比其他路径长出2倍,是接近平衡的,性质决定的

    性质

    每个结点不是红色就是黑色
    根节点是黑色的
    如果一个节点是红色的,则它的两个孩子结点是黑色的
    对于每个结点,从该结点到其所有后代叶结点的简单路径上,均包含相同数目的黑色结点
    每个叶子结点都是黑色的(此处的叶子结点指的是空结点),所以一条路径走完是走到nullptr才结束

    首先定义一个枚举类型,来确定节点颜色

    其次则是定义一个结构体类型,来封装节点 

    然后采用类模板的方式来封装类

    和AVL树一样,红黑树也比较复杂,库里面有,所以只写插入,简单了解其过程即可

    首先如果是一颗空树,则直接插入节点,节点颜色定为黑色

    然后其余情况则是先按照二叉搜索树的插入过程插入节点,插入红节点比插入黑节点更便于后面维持平衡时修改红黑树结构,所以初始时插入红节点

    父亲节点存在且为红,主要是看叔叔节点来控制平衡

    如果父亲节点是爷爷节点的左节点,分几种情况来讨论

    叔叔节点存在且为红

    将父亲节点和叔叔节点都变黑,然后将祖父节点变红,如果祖父节点不是根节点,则还需继续向上调整,出循环后,将根节点变黑即可 

    叔叔节点不存在或者为黑时,只变色无法维持平衡了,那么则需通过旋转来维持平衡

    不存在时

    右单旋,然后将祖父节点变红,父亲节点变黑即可

    存在且为黑时

     先向上调整颜色,然后右单旋,最后将父亲节点变黑,祖父节点变红即可

    上述两种其实算是一种情况,所以代码如上图所示

    不存在,且新增节点是父亲节点的右孩子时

    先左单旋,然后右单旋,最后将新增节点变黑,祖父节点变红即可

    存在且为黑,且cur是其父亲节点的右孩子时

    先向上调整变色,然后先左单旋,然后右单选,最后将cur节点变黑,祖父节点变红即可

    上述两种情况其实算一种情况,所以代码如上图所示

    如果父亲节点是爷爷节点的右节点,也分几种情况来讨论

    叔叔节点存在且为红

     将父亲节点和叔叔节点都变黑,然后将祖父节点变红,如果祖父节点不是根节点,则还需继续向上调整,出循环后,将根节点变黑即可 

    叔叔节点不存在或者为黑时,只变色无法维持平衡了,那么则需通过旋转来维持平衡

    不存在时

    左单旋,然后将祖父节点变红,父亲节点变黑即可

    存在且为黑时

    先向上调整颜色,然后左单旋,最后将父亲节点变黑,祖父节点变红即可

    上述两种其实算是一种情况,所以代码如上图所示

    不存在,且新增节点是父亲节点的左孩子时

    先右单旋,然后左单旋,最后将新增节点变黑,祖父节点变红即可

    存在且为黑,且cur是其父亲节点的左孩子时

     先向上调整变色,然后先左单旋,然后右单选,最后将cur节点变黑,祖父节点变红即可

    上述两种情况其实算一种情况,所以代码如上图所示

    如果父亲节点是爷爷节点的右节点,也分几种情况来讨论

    注意:上述红黑树的旋转函数,只需将AVL树的左旋转和右旋转拷贝过来,然后把调整平衡因子的语句删掉即可

    检验是否是红黑树

    一个是检验它是否是二叉搜索树,另外则是判读是否符合红黑树的性质

    检验是否是二叉搜索树只需写一个中序遍历,看是否有序即可

    检验是否符合红黑树的性质

    检验第二条性质,第一条和第五条都无需检验了

    检验第三条性质

    判断它的两个孩子比较难处理,可以转换为检验它的父亲节点的颜色,只要它和它父亲节点颜色一致,则不满足第三条性质

     检验第四条性质

    首先需算出其中一条路径的黑色节点个数,然后以此为基准,判断其它路径的黑色节点与此路径的黑色节点个数是否相等即可,这里以最左路径为基准,然后将最左路径的黑色节点个数作为参数传给子函数,同时定义了blackNum,来统计黑色节点个数,作为子函数的形参

    这里要采用二叉数的深度遍历,来统计每一条路径的黑色节点个数,当走完一条路径后,然后用它与最左路径的黑色节点个数作比较,相等则符合第四条性质,不相等则不符合

     

    注意:上述的blackNum一定不能传引用给子函数,只能作其的形参才能验证此性质

    红黑树封装map和set

    因为一棵红黑树要同时封装map和set,所以红黑树的节点封装有些变化,如下图

    同时还需要写一个迭代器,T对应是T,Ref对应是T&,Ptr对应是T* 

    对*运算符的重载,主要是为了应用于set中,得到set中存的数据

    对->运算符的重载,主要是为了应用于map中,因为map中存的是pair,所以返回的pair的地址,本来要得到pair中的first或者second需要两个->,因为编译器优化了,所以解引用时只需要一个->即可

    判断两个节点相不相等,比较它们两个的地址即可

    重载++运算符

    其实就是按中序遍历的路径走

     重载--运算符

     上述++和--运算符的重载,其实思路是一致的

    因为map和set存储的数据不一样,所以在红黑树的模板参数中多加了一个仿函数的模板参数

    同时有const迭代器和普通迭代器

     

     

    初始节点应该是红黑树的最左节点,而结尾是最右节点,也就是nullptr结尾的,所以结尾以nullptr结束

     

    拷贝构造

    如果开始是一颗空树,则直接返回nullptr即可,否则则先拷贝它的根节点,及其保持颜色一致,然后再左右分别递归下去,然后则是子节点与父亲节点的连接,最后返回根节点即可

    赋值运算符重载

    首先是实参传给形参的时候,会拷贝构造出一颗树,然后直接将其构造的树的根节点与待要被赋值的树的根节点作交换即可

    析构函数

    首先对红黑树进行一次遍历,将其节点全部销毁,最后再将根节点置为nullptr即可

    首先map有两个模板参数,key和value

    其余的像begin(),end(),insert()等等直接复用即可

    重载[]运算符

    []有修改value或者是插入元素pair的作用

    全部代码

    1. //AVL
    2. #pragma once
    3. template<class K,class V>
    4. struct AVLTreeNode
    5. {
    6. AVLTreeNode<K, V>* _left;
    7. AVLTreeNode<K, V>* _right;
    8. AVLTreeNode<K, V>* _parent;
    9. pair<K, V> _kv;
    10. int _bf; //balance factor
    11. AVLTreeNode(const pair<K,V>& kv):_left(nullptr),_right(nullptr),_parent(nullptr),_bf(0),_kv(kv)
    12. {}
    13. };
    14. template<class K ,class V>
    15. class AVLTree
    16. {
    17. typedef AVLTreeNode<K, V> Node;
    18. public:
    19. AVLTree():_root(nullptr)
    20. {}
    21. bool Insert(const pair<K, V>& kv)
    22. {
    23. if (_root == nullptr)
    24. {
    25. _root = new Node(kv);
    26. return true;
    27. }
    28. Node* parent = nullptr;
    29. Node* cur = _root;
    30. while (cur)
    31. {
    32. if (cur->_kv.first < kv.first)
    33. {
    34. parent = cur;
    35. cur = cur->_right;
    36. }
    37. else if (cur->_kv.first > kv.first)
    38. {
    39. parent = cur;
    40. cur = cur->_left;
    41. }
    42. else
    43. {
    44. return false;
    45. }
    46. }
    47. cur = new Node(kv);
    48. if (parent->_kv.first < kv.first)
    49. {
    50. parent->_right = cur;
    51. cur->_parent = parent;
    52. }
    53. else
    54. {
    55. parent->_left = cur;
    56. cur->_parent = parent;
    57. }
    58. //控制平衡
    59. //1.更新平衡因子 -- 新增节点到根节点的祖先路径
    60. //2.出现异常平衡因子,那么需要旋转平衡处理
    61. while (parent)
    62. {
    63. if (cur == parent->_left)
    64. parent->_bf--;
    65. else
    66. parent->_bf++;
    67. if (parent->_bf == 0)
    68. {
    69. break;
    70. }
    71. else if (parent->_bf == 1 || parent->_bf == -1)
    72. {
    73. //继续往上更新
    74. cur = parent;
    75. parent = parent->_parent;
    76. }
    77. else if (parent->_bf == 2 || parent->_bf == -2)
    78. {
    79. //旋转处理
    80. //右单旋
    81. if (parent->_bf == -2 && cur->_bf == -1)
    82. {
    83. RotateR(parent);
    84. }
    85. //左单旋
    86. else if (parent->_bf == 2 && cur->_bf == 1)
    87. {
    88. RotateL(parent);
    89. }
    90. else if (parent->_bf == -2 && cur->_bf == 1)
    91. {
    92. RotateLR(parent);
    93. }
    94. else if (parent->_bf == 2 && cur->_bf == -1)
    95. {
    96. RotateRL(parent);
    97. }
    98. else
    99. {
    100. assert(false);
    101. }
    102. break;
    103. }
    104. else
    105. {
    106. //说明插入更新平衡因子之前,树中平衡因子就有问题了
    107. assert(false);
    108. }
    109. }
    110. return true;
    111. }
    112. void RotateL(Node* parent)
    113. {
    114. Node* subR = parent->_right;
    115. Node* subRL = subR->_left;
    116. parent->_right = subRL;
    117. if (subRL)
    118. {
    119. subRL->_parent = parent;
    120. }
    121. Node* parentParent = parent->_parent;
    122. subR->_left = parent;
    123. parent->_parent = subR;
    124. if (_root == parent)
    125. {
    126. _root = subR;
    127. subR->_parent = nullptr;
    128. }
    129. else
    130. {
    131. if (parentParent->_left == parent)
    132. {
    133. parentParent->_left = subR;
    134. }
    135. else
    136. {
    137. parentParent->_right = subR;
    138. }
    139. subR->_parent = parentParent;
    140. }
    141. subR->_bf = parent->_bf = 0;
    142. }
    143. void RotateR(Node* parent)
    144. {
    145. Node* subL = parent->_left;
    146. Node* subLR = subL->_right;
    147. parent->_left = subLR;
    148. if (subLR)
    149. {
    150. subLR->_parent = parent;
    151. }
    152. Node* parentParent = parent->_parent;
    153. subL->_right = parent;
    154. parent->_parent = subL;
    155. if (_root == parent)
    156. {
    157. _root = subL;
    158. _root->_parent = nullptr;
    159. }
    160. else
    161. {
    162. if (parentParent->_left == parent)
    163. {
    164. parentParent->_left = subL;
    165. }
    166. else
    167. {
    168. parentParent->_right = subL;
    169. }
    170. subL->_parent = parentParent;
    171. }
    172. subL->_bf = parent->_bf = 0;
    173. }
    174. void RotateLR(Node* parent)
    175. {
    176. Node* subL = parent->_left;
    177. Node* subLR = subL->_right;
    178. int bf = subLR->_bf;
    179. RotateL(parent->_left);
    180. RotateR(parent);
    181. if (bf == 1)
    182. {
    183. parent->_bf = 0;
    184. subL->_bf = -1;
    185. subLR->_bf = 0;
    186. }
    187. else if (bf == -1)
    188. {
    189. parent->_bf = 1;
    190. subL->_bf = 0;
    191. subLR->_bf = 0;
    192. }
    193. else if (bf == 0)
    194. {
    195. parent->_bf = 0;
    196. subL->_bf = 0;
    197. subLR->_bf = 0;
    198. }
    199. else
    200. {
    201. assert(false);
    202. }
    203. }
    204. void RotateRL(Node* parent)
    205. {
    206. Node* subR = parent->_right;
    207. Node* subRL = subR->_left;
    208. int bf = subRL->_bf;
    209. RotateR(parent->_right);
    210. RotateL(parent);
    211. if (bf == 1)
    212. {
    213. parent->_bf = -1;
    214. subR->_bf = 0;
    215. subRL->_bf = 0;
    216. }
    217. else if (bf == -1)
    218. {
    219. parent->_bf = 0;
    220. subR->_bf = 1;
    221. subRL->_bf = 0;
    222. }
    223. else if (bf == 0)
    224. {
    225. parent->_bf = 0;
    226. subR->_bf = 0;
    227. subRL->_bf = 0;
    228. }
    229. else
    230. {
    231. assert(false);
    232. }
    233. }
    234. void InOrder()
    235. {
    236. _InOrder(_root);
    237. }
    238. void _InOrder(Node* root)
    239. {
    240. if (root == nullptr)
    241. {
    242. return;
    243. }
    244. _InOrder(root->_left);
    245. cout << root->_kv.first << ":" << root->_kv.second << endl;
    246. _InOrder(root->_right);
    247. }
    248. bool IsBalance()
    249. {
    250. return _IsBalance(_root);
    251. }
    252. int Height(Node* root)
    253. {
    254. if (root == nullptr)
    255. {
    256. return 0;
    257. }
    258. int leftHeight = Height(root->_left);
    259. int rightHeight = Height(root->_right);
    260. return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
    261. }
    262. bool _IsBalance(Node* root)
    263. {
    264. if (root == nullptr)
    265. {
    266. return true;
    267. }
    268. //对当前树进行检查
    269. int leftHeight = Height(root->_left);
    270. int rightHeight = Height(root->_right);
    271. if (rightHeight - leftHeight != root->_bf)
    272. {
    273. cout << root->_kv.first << "现在是:" << root->_bf << endl;
    274. cout << root->_kv.first << "现在是:" << rightHeight - leftHeight << endl;
    275. return false;
    276. }
    277. return abs(rightHeight - leftHeight) < 2
    278. && _IsBalance(root->_left)
    279. && _IsBalance(root->_right);
    280. }
    281. private:
    282. Node* _root;
    283. };
    284. void TestAVLTree()
    285. {
    286. AVLTree<int, int> t;
    287. //int a[] = { 5,4,3,2,1,0 };
    288. //int a[] = { 16,3,7,11,9,26,18,14,15 };
    289. int a[] = { 4,2,6,1,3,5,15,7,16,14 };
    290. for (auto e : a)
    291. {
    292. t.Insert(make_pair(e, e));
    293. cout << "Insert" << e << ":" << t.IsBalance() << endl;
    294. }
    295. t.InOrder();
    296. cout << t.IsBalance() << endl;
    297. }
    298. //红黑树-副本
    299. #pragma once
    300. #include<time.h>
    301. enum Colour
    302. {
    303. RED,
    304. BLACK
    305. };
    306. template<class K , class V>
    307. struct RBTreeNode
    308. {
    309. RBTreeNode<K,V>* _left;
    310. RBTreeNode<K,V>* _right;
    311. RBTreeNode<K,V>* _parent;
    312. pair<K, V> _kv;
    313. Colour _col;
    314. RBTreeNode(const pair<K,V>& kv) :_left(nullptr), _right(nullptr), _parent(nullptr), _col(RED), _kv(kv)
    315. {}
    316. };
    317. template<class K,class V>
    318. struct RBTree
    319. {
    320. typedef RBTreeNode<K, V> Node;
    321. public:
    322. RBTree() :_root(nullptr)
    323. {}
    324. bool Insert(const pair<K,V>& kv)
    325. {
    326. if (_root == nullptr)
    327. {
    328. _root = new Node(kv);
    329. _root->_col = BLACK;
    330. return true;
    331. }
    332. Node* parent = nullptr;
    333. Node* cur = _root;
    334. while (cur)
    335. {
    336. if (cur->_kv.first < kv.first)
    337. {
    338. parent = cur;
    339. cur = cur->_right;
    340. }
    341. else if (cur->_kv.first > kv.first)
    342. {
    343. parent = cur;
    344. cur = cur->_left;
    345. }
    346. else
    347. {
    348. return false;
    349. }
    350. }
    351. cur = new Node(kv);
    352. cur->_col = RED; //新增节点
    353. if (parent->_kv.first < kv.first)
    354. {
    355. parent->_right = cur;
    356. cur->_parent = parent;
    357. }
    358. else
    359. {
    360. parent->_left = cur;
    361. cur->_parent = parent;
    362. }
    363. //控制平衡
    364. while (parent && parent->_col == RED)
    365. {
    366. Node* grandfather = parent->_parent;
    367. if (parent == grandfather->_left)
    368. {
    369. Node* uncle = grandfather->_right;
    370. //1.uncle存在且为红
    371. if (uncle && uncle->_col == RED)
    372. {
    373. //变色+继续向上处理
    374. parent->_col = uncle->_col = BLACK;
    375. grandfather->_col = RED;
    376. cur = grandfather;
    377. parent = cur->_parent;
    378. }
    379. else //2 + 3、uncle不存在/存在且为黑
    380. {
    381. // g
    382. // p
    383. // c
    384. // g
    385. // p
    386. // c
    387. if (cur == parent->_left)
    388. {
    389. //单旋
    390. RotateR(grandfather);
    391. parent->_col = BLACK;
    392. grandfather->_col = RED;
    393. }
    394. else
    395. {
    396. //双旋
    397. RotateL(parent);
    398. RotateR(grandfather);
    399. cur->_col = BLACK;
    400. grandfather->_col = RED;
    401. }
    402. break;
    403. }
    404. }
    405. else //parent == grandfather->_right
    406. {
    407. Node* uncle = grandfather->_left;
    408. if (uncle && uncle->_col == RED)
    409. {
    410. //变色+继续向上处理
    411. parent->_col = uncle->_col = BLACK;
    412. grandfather->_col = RED;
    413. cur = grandfather;
    414. parent = cur->_parent;
    415. }
    416. else // 2 + 3、uncle不存在/ 存在且为黑
    417. {
    418. // g
    419. // p
    420. // c
    421. //g
    422. // p
    423. //c
    424. if (cur == parent->_right)
    425. {
    426. RotateL(grandfather);
    427. parent->_col = BLACK;
    428. grandfather->_col = RED;
    429. }
    430. else
    431. {
    432. RotateR(parent);
    433. RotateL(grandfather);
    434. cur->_col = BLACK;
    435. grandfather->_col = RED;
    436. }
    437. break;
    438. }
    439. }
    440. }
    441. _root->_col = BLACK;
    442. return true;
    443. }
    444. void RotateL(Node* parent)
    445. {
    446. Node* subR = parent->_right;
    447. Node* subRL = subR->_left;
    448. parent->_right = subRL;
    449. if (subRL)
    450. {
    451. subRL->_parent = parent;
    452. }
    453. Node* parentParent = parent->_parent;
    454. subR->_left = parent;
    455. parent->_parent = subR;
    456. if (_root == parent)
    457. {
    458. _root = subR;
    459. subR->_parent = nullptr;
    460. }
    461. else
    462. {
    463. if (parentParent->_left == parent)
    464. {
    465. parentParent->_left = subR;
    466. }
    467. else
    468. {
    469. parentParent->_right = subR;
    470. }
    471. subR->_parent = parentParent;
    472. }
    473. }
    474. void RotateR(Node* parent)
    475. {
    476. Node* subL = parent->_left;
    477. Node* subLR = subL->_right;
    478. parent->_left = subLR;
    479. if (subLR)
    480. {
    481. subLR->_parent = parent;
    482. }
    483. Node* parentParent = parent->_parent;
    484. subL->_right = parent;
    485. parent->_parent = subL;
    486. if (_root == parent)
    487. {
    488. _root = subL;
    489. _root->_parent = nullptr;
    490. }
    491. else
    492. {
    493. if (parentParent->_left == parent)
    494. {
    495. parentParent->_left = subL;
    496. }
    497. else
    498. {
    499. parentParent->_right = subL;
    500. }
    501. subL->_parent = parentParent;
    502. }
    503. }
    504. void InOrder()
    505. {
    506. _InOrder(_root);
    507. }
    508. void _InOrder(Node* root)
    509. {
    510. if (root == nullptr)
    511. {
    512. return;
    513. }
    514. _InOrder(root->_left);
    515. cout << root->_kv.first << ":" << root->_kv.second << endl;
    516. _InOrder(root->_right);
    517. }
    518. bool IsBalance()
    519. {
    520. if (_root && _root->_col == RED)
    521. {
    522. cout << "根节点不是黑色" << endl;
    523. return false;
    524. }
    525. //最左路径黑色节点数量做基准值
    526. int banchmark = 0;
    527. Node* left = _root;
    528. while (left)
    529. {
    530. if (left->_col == BLACK)
    531. ++banchmark;
    532. left = left->_left;
    533. }
    534. int blackNum = 0;
    535. return _IsBalance(_root, banchmark, blackNum);
    536. }
    537. bool _IsBalance(Node* root,int banchmark,int blackNum)
    538. {
    539. if (root == nullptr)
    540. {
    541. if (banchmark != blackNum)
    542. {
    543. cout << "存在路径黑色节点的数量不相等" << endl;
    544. return false;
    545. }
    546. return true;
    547. }
    548. if (root->_col == RED && root->_parent->_col == RED)
    549. {
    550. cout << "出现连续红色节点" << endl;
    551. return false;
    552. }
    553. if (root->_col == BLACK)
    554. {
    555. ++blackNum;
    556. }
    557. return _IsBalance(root->_left, banchmark, blackNum) && _IsBalance(root->_right, banchmark, blackNum);
    558. }
    559. int Height()
    560. {
    561. return _Height(_root);
    562. }
    563. int _Height(Node* root)
    564. {
    565. if (root == nullptr)
    566. return 0;
    567. int leftHeight = _Height(root->_left);
    568. int rightHeight = _Height(root->_right);
    569. return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
    570. }
    571. private:
    572. Node* _root;
    573. };
    574. void TestRBTree()
    575. {
    576. RBTree<int, int> t;
    577. vector<int> v;
    578. srand(time(0));
    579. int N = 10000;
    580. for (int i = 0; i < N; i++)
    581. {
    582. //v.push_back(rand());
    583. v.push_back(i);
    584. }
    585. //int a[] = { 5,4,3,2,1,0 };
    586. //int a[] = { 16,3,7,11,9,26,18,14,15 };
    587. //int a[] = { 4,2,6,1,3,5,15,7,16,14 };
    588. for (auto e : v)
    589. {
    590. t.Insert(make_pair(e, e));
    591. if (!t.IsBalance())
    592. {
    593. cout << "Insert" << e << endl;
    594. }
    595. }
    596. t.InOrder();
    597. //cout << t.IsBalance() << endl;
    598. cout << "高度:" << t.Height() << endl;
    599. }
    600. //改善后的红黑树
    601. #pragma once
    602. #include<time.h>
    603. enum Colour
    604. {
    605. RED,
    606. BLACK
    607. };
    608. template<class T>
    609. struct RBTreeNode
    610. {
    611. RBTreeNode<T>* _left;
    612. RBTreeNode<T>* _right;
    613. RBTreeNode<T>* _parent;
    614. T _data;
    615. Colour _col;
    616. RBTreeNode(const T& data):_left(nullptr),_right(nullptr),_parent(nullptr),_col(RED),_data(data)
    617. {}
    618. };
    619. template<class T,class Ref,class Ptr>
    620. struct RBTreeIterator
    621. {
    622. typedef RBTreeNode<T> Node;
    623. typedef RBTreeIterator<T, Ref, Ptr> Self;
    624. Node* _node;
    625. RBTreeIterator(Node* node):_node(node)
    626. {}
    627. Ref operator*()
    628. {
    629. return _node->_data;
    630. }
    631. Ptr operator->()
    632. {
    633. return &_node->_data;
    634. }
    635. Self& operator++()
    636. {
    637. if (_node->_right)
    638. {
    639. Node* min = _node->_right;
    640. while (min->_left)
    641. {
    642. min = min->_left;
    643. }
    644. _node = min;
    645. }
    646. else
    647. {
    648. Node* cur = _node;
    649. Node* parent = cur->_parent;
    650. while (parent && cur == parent->_right)
    651. {
    652. cur = cur->_parent;
    653. parent = parent->_parent;
    654. }
    655. _node = parent;
    656. }
    657. return *this;
    658. }
    659. Self& operator--()
    660. {
    661. if (_node->_left)
    662. {
    663. Node* max = _node->left;
    664. while (max->_right)
    665. {
    666. max = max->_right;
    667. }
    668. _node = max;
    669. }
    670. else
    671. {
    672. Node* cur = _node;
    673. Node* parent = cur->_parent;
    674. while (parent && cur == parent->_left)
    675. {
    676. cur = parent;
    677. parent = parent->_parent;
    678. }
    679. _node = parent;
    680. }
    681. return *this;
    682. }
    683. bool operator==(const Self& s)const
    684. {
    685. return _node == s._node;
    686. }
    687. bool operator!=(const Self& s)const
    688. {
    689. return _node != s._node;
    690. }
    691. };
    692. //set RBTree<K, K, SetKeyOfT>
    693. //map RBTree<K, pair<K,V>, MapKeyOfT>
    694. template<class K,class T,class KeyOfT>
    695. struct RBTree
    696. {
    697. typedef RBTreeNode<T> Node;
    698. public:
    699. typedef RBTreeIterator<T, T&, T*> iterator;
    700. typedef RBTreeIterator<T, const T&,const T*> const_iterator;
    701. iterator begin()
    702. {
    703. Node* min = _root;
    704. while (min && min->_left)
    705. {
    706. min = min->_left;
    707. }
    708. return iterator(min);
    709. }
    710. iterator end()
    711. {
    712. return iterator(nullptr);
    713. }
    714. RBTree():_root(nullptr)
    715. {}
    716. RBTree(const RBTree<K, T, KeyOfT>& t)
    717. {
    718. _root = Copy(t._root);
    719. }
    720. RBTree<K, T, KeyOfT>& operator=(RBTree<K, T, KeyOfT> t)
    721. {
    722. swap(_root, t._root);
    723. return *this;
    724. }
    725. ~RBTree()
    726. {
    727. Destroy(_root);
    728. _root = nullptr;
    729. }
    730. iterator Find(const K& key)
    731. {
    732. Node* cur = _root;
    733. KeyOfT kot;
    734. while (cur)
    735. {
    736. if (kot(cur->_data) < key)
    737. {
    738. cur = cur->_right;
    739. }
    740. else if (kot(cur->_data) > key)
    741. {
    742. cur = cur->_left;
    743. }
    744. else
    745. {
    746. return iterator(cur);
    747. }
    748. }
    749. return end();
    750. }
    751. pair<iterator,bool> Insert(const T& data)
    752. {
    753. if (_root == nullptr)
    754. {
    755. _root = new Node(data);
    756. _root->_col = BLACK;
    757. return make_pair(iterator(_root),true);
    758. }
    759. KeyOfT kot;
    760. Node* parent = nullptr;
    761. Node* cur = _root;
    762. while (cur)
    763. {
    764. if (kot(cur->_data) < kot(data))
    765. {
    766. parent = cur;
    767. cur = cur->_right;
    768. }
    769. else if (kot(cur->_data) > kot(data))
    770. {
    771. parent = cur;
    772. cur = cur->_left;
    773. }
    774. else
    775. {
    776. return make_pair(iterator(_root), false);
    777. }
    778. }
    779. cur = new Node(data);
    780. Node* newnode = cur;
    781. cur->_col = RED; //新增节点
    782. if (kot(parent->_data) < kot(data))
    783. {
    784. parent->_right = cur;
    785. cur->_parent = parent;
    786. }
    787. else
    788. {
    789. parent->_left = cur;
    790. cur->_parent = parent;
    791. }
    792. //控制平衡
    793. while (parent && parent->_col == RED)
    794. {
    795. Node* grandfather = parent->_parent;
    796. if (parent == grandfather->_left)
    797. {
    798. Node* uncle = grandfather->_right;
    799. //1.uncle存在且为红
    800. if (uncle && uncle->_col == RED)
    801. {
    802. //变色+继续向上处理
    803. parent->_col = uncle->_col = BLACK;
    804. grandfather->_col = RED;
    805. cur = grandfather;
    806. parent = cur->_parent;
    807. }
    808. else //2 + 3、uncle不存在/存在且为黑
    809. {
    810. // g
    811. // p
    812. // c
    813. // g
    814. // p
    815. // c
    816. if (cur == parent->_left)
    817. {
    818. //单旋
    819. RotateR(grandfather);
    820. parent->_col = BLACK;
    821. grandfather->_col = RED;
    822. }
    823. else
    824. {
    825. //双旋
    826. RotateL(parent);
    827. RotateR(grandfather);
    828. cur->_col = BLACK;
    829. grandfather->_col = RED;
    830. }
    831. break;
    832. }
    833. }
    834. else //parent == grandfather->_right
    835. {
    836. Node* uncle = grandfather->_left;
    837. if (uncle && uncle->_col == RED)
    838. {
    839. //变色+继续向上处理
    840. parent->_col = uncle->_col = BLACK;
    841. grandfather->_col = RED;
    842. cur = grandfather;
    843. parent = cur->_parent;
    844. }
    845. else // 2 + 3、uncle不存在/ 存在且为黑
    846. {
    847. // g
    848. // p
    849. // c
    850. //g
    851. // p
    852. //c
    853. if (cur == parent->_right)
    854. {
    855. RotateL(grandfather);
    856. parent->_col = BLACK;
    857. grandfather->_col = RED;
    858. }
    859. else
    860. {
    861. RotateR(parent);
    862. RotateL(grandfather);
    863. cur->_col = BLACK;
    864. grandfather->_col = RED;
    865. }
    866. break;
    867. }
    868. }
    869. }
    870. _root->_col = BLACK;
    871. return make_pair(iterator(newnode), true);
    872. }
    873. private:
    874. void RotateL(Node* parent)
    875. {
    876. Node* subR = parent->_right;
    877. Node* subRL = subR->_left;
    878. parent->_right = subRL;
    879. if (subRL)
    880. {
    881. subRL->_parent = parent;
    882. }
    883. Node* parentParent = parent->_parent;
    884. subR->_left = parent;
    885. parent->_parent = subR;
    886. if (_root == parent)
    887. {
    888. _root = subR;
    889. subR->_parent = nullptr;
    890. }
    891. else
    892. {
    893. if (parentParent->_left == parent)
    894. {
    895. parentParent->_left = subR;
    896. }
    897. else
    898. {
    899. parentParent->_right = subR;
    900. }
    901. subR->_parent = parentParent;
    902. }
    903. }
    904. void RotateR(Node* parent)
    905. {
    906. Node* subL = parent->_left;
    907. Node* subLR = subL->_right;
    908. parent->_left = subLR;
    909. if (subLR)
    910. {
    911. subLR->_parent = parent;
    912. }
    913. Node* parentParent = parent->_parent;
    914. subL->_right = parent;
    915. parent->_parent = subL;
    916. if (_root == parent)
    917. {
    918. _root = subL;
    919. _root->_parent = nullptr;
    920. }
    921. else
    922. {
    923. if (parentParent->_left == parent)
    924. {
    925. parentParent->_left = subL;
    926. }
    927. else
    928. {
    929. parentParent->_right = subL;
    930. }
    931. subL->_parent = parentParent;
    932. }
    933. }
    934. void Destroy(Node* root)
    935. {
    936. if (root == nullptr)
    937. {
    938. return;
    939. }
    940. Destroy(root->_left);
    941. Destroy(root->_right);
    942. delete root;
    943. }
    944. Node* Copy(Node* root)
    945. {
    946. if (root == nullptr)
    947. return nullptr;
    948. Node* newRoot = new Node(root->_data);
    949. newRoot->_col = root->_col;
    950. newRoot->_left = Copy(root->_left);
    951. newRoot->_right = Copy(root->_right);
    952. if (newRoot->_left)
    953. newRoot->_left->_parent = newRoot;
    954. if (newRoot->_right)
    955. newRoot->_right->_parent = newRoot;
    956. return newRoot;
    957. }
    958. private:
    959. Node* _root;
    960. };
    961. //map
    962. #pragma once
    963. #include"RBTree.h"
    964. namespace bit
    965. {
    966. template<class K,class V>
    967. class map
    968. {
    969. public:
    970. struct MapKeyOfT
    971. {
    972. const K& operator()(const pair<K, V>& kv)
    973. {
    974. return kv.first;
    975. }
    976. };
    977. typedef typename RBTree<K, pair<K,V>,MapKeyOfT>::iterator iterator;
    978. iterator begin()
    979. {
    980. return _t.begin();
    981. }
    982. iterator end()
    983. {
    984. return _t.end();
    985. }
    986. pair<iterator,bool> insert(const pair<K, V>& kv)
    987. {
    988. return _t.Insert(kv);
    989. }
    990. iterator find(const K& key)
    991. {
    992. return _t.Find(key);
    993. }
    994. V& operator[](const K& key)
    995. {
    996. auto ret = _t.Insert(make_pair(key, V()));
    997. return ret.first->second;
    998. }
    999. private:
    1000. RBTree<K, pair<K, V>, MapKeyOfT> _t;
    1001. };
    1002. void test_map()
    1003. {
    1004. map<string, string> dict;
    1005. //dict.insert(make_pair("sort", "排序"));
    1006. //dict.insert(make_pair("string", "字符串"));
    1007. //dict.insert(make_pair("map", "地图"));
    1008. //dict["left"];
    1009. dict["left"] = "晚";
    1010. //dict["map"] = "fsgd";
    1011. auto it = dict.begin();
    1012. while (it != dict.end())
    1013. {
    1014. cout << it->first << ":" << it->second << endl;
    1015. ++it;
    1016. }
    1017. cout << endl;
    1018. }
    1019. }
    1020. //set
    1021. #pragma once
    1022. #include"RBTree.h"
    1023. namespace bit
    1024. {
    1025. template<class K>
    1026. class set
    1027. {
    1028. public:
    1029. struct SetKeyOfT
    1030. {
    1031. const K& operator()(const K& k)
    1032. {
    1033. return k;
    1034. }
    1035. };
    1036. typedef typename RBTree<K, K, SetKeyOfT>::iterator iterator;
    1037. iterator begin()
    1038. {
    1039. return _t.begin();
    1040. }
    1041. iterator end()
    1042. {
    1043. return _t.end();
    1044. }
    1045. pair<iterator,bool> insert(const K& key)
    1046. {
    1047. return _t.Insert(key);
    1048. }
    1049. iterator find(const K& key)
    1050. {
    1051. return _t.Find(key);
    1052. }
    1053. private:
    1054. RBTree<K, K, SetKeyOfT> _t;
    1055. };
    1056. void test_set()
    1057. {
    1058. set<int> s;
    1059. s.insert(1);
    1060. s.insert(4);
    1061. s.insert(2);
    1062. s.insert(24);
    1063. s.insert(2);
    1064. s.insert(12);
    1065. s.insert(6);
    1066. set<int>::iterator it = s.begin();
    1067. while (it != s.end())
    1068. {
    1069. cout << *it << " ";
    1070. ++it;
    1071. }
    1072. cout << endl;
    1073. for (auto e : s)
    1074. {
    1075. cout << e << " ";
    1076. }
    1077. cout << endl;
    1078. set<int> copy(s);
    1079. for (auto e : copy)
    1080. {
    1081. cout << e << " ";
    1082. }
    1083. cout << endl;
    1084. set<int> ss;
    1085. ss.insert(111);
    1086. ss.insert(422);
    1087. copy = ss;
    1088. for (auto e : copy)
    1089. {
    1090. cout << e << " ";
    1091. }
    1092. cout << endl;
    1093. }
    1094. }
  • 相关阅读:
    常用的 Linux 命令
    分类预测 | MATLAB实现SSA-CNN-BiLSTM麻雀算法优化卷积双向长短期记忆神经网络数据分类预测
    RabbitMQ原理和架构图解(附6大工作模式)
    es-head插件插入查询以及条件查询(五)
    Linux - find命令详解
    python数据可视化-matplotlib入门(6)-从文件中加载数据
    Day15--加入购物车-初始化vuex
    【机器学习】sklearn特征值选取与处理
    FSOD论文阅读 - 基于卷积和注意力机制的小样本目标检测
    剑指 Offer 56 数组中数字出现的次数(异或)
  • 原文地址:https://blog.csdn.net/weixin_58867976/article/details/125434552