第一章:关联式容器
在初阶阶段,我们已经接触过STL中的部分容器,比如:vector、list、deque、forward_list(C++11)等,这些容器统称为序列式容器,因为其底层为线性序列的数据结构,里面存储的是元素本身。那什么是关联式容器?它与序列式容器有什么区别?
关联式容器也是用来存储数据的,与序列式容器不同的是,其里面存储的是<key, value>结构的键值对,在数据检索时比序列式容器效率更高。
第二章:键值对
用来表示具有一一对应关系的一种结构,该结构中一般只包含两个成员变量key和value,key代表键值,value表示与key对应的信息。比如:现在要建立一个英汉互译的字典,那该字典中必然有英文单词与其对应的中文含义,而且,英文单词与其中文含义是一一对应的关系,即通过该应该单词,在词典中就可以找到与其对应的中文含义。
SGI-STL中关于键值对的定义:
template <class T1, class T2>
struct pair {
typedef T1 first_type;
typedef T2 second_type;
T1 first;
T2 second;
pair() : first(T1()), second(T2()) {}
pair(const T1& a, const T2& b) : first(a), second(b) {}
};
第三章:树形结构的关联式容
3.1 set
3.1.1 set的介绍
翻译:
- set是按照一定次序存储元素的容器
- 在set中,元素的value也标识它(value就是key,类型为T),并且每个value必须是唯一的。set中的元素不能在容器中修改(元素总是const),但是可以从容器中插入或删除它们。
- 在内部,set中的元素总是按照其内部比较对象(类型比较)所指示的特定严格弱排序准则进行排序。
- set容器通过key访问单个元素的速度通常比unordered_set容器慢,但它们允许根据顺序对子集进行直接迭代。
- set在底层是用二叉搜索树(红黑树)实现的。
注意:
- 与map/multimap不同,map/multimap中存储的是真正的键值对<key, value>,set中只放value,但在底层实际存放的是由<value, value>构成的键值对。
- set中插入元素时,只需要插入value即可,不需要构造键值对。
- set中的元素不可以重复(因此可以使用set进行去重)。
- 使用set的迭代器遍历set中的元素,可以得到有序序列
- set中的元素默认按照小于来比较
- set中查找某个元素,时间复杂度为:$log_2 n$
- set中的元素不允许修改(为什么?)
- set中的底层使用二叉搜索树(红黑树)来实现
3.1.2 set的使用
1. set的模板参数列表

T:set中存放元素的类型,实际在底层存储<value, value>的键值对。
Compare:set中元素默认按照小于来比较
Alloc:set中元素空间的管理方式,使用STL提供的空间配置器管理
2. set的构造
|
函数声明
|
功能介绍
|
| set (const Compare& comp = Compare(), const Allocator& = Allocator() ); |
构造空的
set
|
| set (InputIterator first, InputIterator last, const Compare& comp = Compare(), const Allocator& = Allocator() ); | 用[first, last)区间中的元素构造set |
| set ( const set<Key,Compare,Allocator>& x); | set的拷贝构造 |
3. set的迭代器
| 函数声明 | 功能介绍 |
| iterator begin() | 返回set中起始位置元素的迭代器 |
| iterator end() | 返回set中最后一个元素后面的迭代器 |
| const_iterator cbegin() const | 返回set中起始位置元素的const迭代器 |
| const_iterator cend() const | 返回set中最后一个元素后面的const迭代器 |
| reverse_iterator rbegin() | 返回set第一个元素的反向迭代器,即end |
| reverse_iterator rend() | 返回set最后一个元素下一个位置的反向迭代器,即rbegin |
| const_reverse_iterator crbegin() const | 返回set第一个元素的反向const迭代器,即cend |
| const_reverse_iterator crend() const | 返回set最后一个元素下一个位置的反向const迭代器,即crbegin |
4. set的容量
| 函数声明 | 功能介绍 |
| bool empty () const | 检测set是否为空,空返回true,否则返回true |
| size_type size() const | 返回set中有效元素的个数 |
5. set修改操作
| 函数声明 | 功能介绍 |
| pair<iterator,bool> insert ( const value_type& x ) | 在set中插入元素x,实际插入的是<x, x>构成的键值对,如果插入成功,返回<该元素在set中的位置,true>,如果插入失败,说明x在set中已经存在,返回<x在set中的位置,false> |
| void erase ( iterator position ) | 删除set中position位置上的元素 |
| size_type erase ( const key_type& x ) | 删除set中值为x的元素,返回删除的元素的个数 |
| void erase ( iterator first, iterator last ) | 删除set中[first, last)区间中的元素 |
| void swap ( set<Key,Compare,Allocator>& st ); | 交换set中的元素 |
| void clear ( ) | 将set中的元素清空 |
| iterator find ( const key_type& x ) | const 返回set中值为x的元素的位置 |
| size_type count ( const key_type& x ) const | 返回set中值为x的元素的个数 |
6. set的使用举例
//set
void test_set1() {
//查找在不在
//排序 + 去重
set<int> s;
s.insert(5);
s.insert(2);
s.insert(6);
s.insert(1);
s.insert(1);//重复值无法插入
s.insert(2);
//pair是insert的返回值,通过查看返回值才知道为什么插入不了
pair<set<int>::iterator, bool> ret1 = s.insert(5);
cout << ret1.second << endl;
auto ret2 = s.insert(5);
cout << ret2.second << endl;
set<int>::iterator it = s.begin();
while (it != s.end()) {
//*it = 10;//set不支持修改
cout << *it << " ";
++it;
}
cout << endl;
//可以使用范围for,因为有迭代器
for (auto e : s)
cout << e << " ";
cout << endl;
s.erase(2);//传value删除。size_type erase (const value_type& val);
s.erase(3);//删除不存在的值,没有影响
it = s.find(3);//找不到返回end()
if (it != s.end())
//如果erase的迭代器无效,会崩溃
s.erase(it);//传迭代器删除。void erase (iterator position);
for (auto e : s)
cout << e << " ";
cout << endl;
//返回val的个数,因为元素都是唯一的,所以只返回1或0
//用count判断元素是否存在
if (s.count(3)) cout << "3在" << endl;
else cout << "3不在" << endl;
}
void test_set2() {
set<int> myset;
set<int>::iterator itlow, itup;
for (int i = 1; i < 10; i++) myset.insert(i * 10); // 10 20 30 40 50 60 70 80 90
itlow = myset.lower_bound(30);//返回30的位置
//itlow = myset.lower_bound(25);//跟30的结果一样,返回第一个>=val位置的迭代器
itup = myset.upper_bound(60);//返回70位置。因为迭代器区间是左闭右开。 返回第一个>val位置的迭代器
//lower_bound和upper_bound返回[30,70)的区间
//虽然erase删除[30,70)左闭右开区间,但从上面的lower_bound和upper_bound参数来看
//可以理解为删除[30,60]的左闭右闭区间
myset.erase(itlow, itup);
cout << "myset contains:";
for (auto e : myset)
cout << e << " ";//10 20 70 80 90
cout << endl;
}
void test_set3() {
set<int> myset;
for (int i = 1; i <= 5; i++) myset.insert(i * 10); // myset: 10 20 30 40 50
pair<set<int>::const_iterator, set<int>::const_iterator> ret;
ret = myset.equal_range(30);
//ret = myset.equal_range(35);//第一和第二返回的都是40
cout << "the lower bound points to: " << *ret.first << '\n';//30 返回>=val
cout << "the upper bound points to: " << *ret.second << '\n';//40 返回>val
}
3.2 map
3.2.1 map的介绍
翻译:
- map是关联容器,它按照特定的次序(按照key来比较)存储由键值key和值value组合而成的元素。
- 在map中,键值key通常用于排序和唯一的标识元素,而值value中存储与此键值key关联的内容。键值key和值value的类型可能不同,并且在map的内部,key与value通过成员类型value_type绑定在一起,为其取别名称为pair:typedef pair<const key, T> value_type;
- 在内部,map中的元素总是按照键值key进行比较排序的。
- map中通过键值访问单个元素的速度通常比unordered_map容器慢,但map允许根据顺序对元素进行直接迭代(即对map中的元素进行迭代时,可以得到一个有序的序列)。
- map支持下标访问符,即在[]中放入key,就可以找到与key对应的value。
- map通常被实现为二叉搜索树(更准确的说:平衡二叉搜索树(红黑树))。
3.2.2 map的使用
1. map的模板参数说明

key:键值对中key的类型
T:键值对中value的类型
Compare:比较器的类型,map中的元素是按照key来比较的,缺省情况下按照小于来比较,一般情况下(内置类型元素)该参数不需要传递,如果无法比较时(自定义类型),需要用户自己显式传递比较规则(一般情况下按照函数指针或者仿函数来传递)
Alloc:通过空间配置器来申请底层空间,不需要用户传递,除非用户不想使用标准库提供的空间配置器
注意:在使用map时,需要包含头文件。
2. map的构造
| 函数声明 | 功能介绍 |
| map() | 构造一个空的map |
3. map的迭代器
| 函数声明 | 功能介绍 |
| begin()和end() | begin:首元素的位置,end最后一个元素的下一个位置 |
| cbegin()和cend() | 与begin和end意义相同,但cbegin和cend所指向的元素不能修改 |
| rbegin()和rend() | 反向迭代器,rbegin在end位置,rend在begin位置,其++和--操作与begin和end操作移动相 |
| crbegin()和crend() | 与rbegin和rend位置相同,操作相同,但crbegin和crend所指向的元素不能修改 |
4. map的容量与元素访问
| 函数声明 | 功能简介 |
| bool empty ( ) const | 检测map中的元素是否为空,是返回true,否则返回false |
| size_type size() const | 返回map中有效元素的个数 |
| mapped_type& operator[] (const key_type& k) | 返回key对应的value |

注意:在元素访问时,有一个与operator[]类似的操作at()(该函数不常用)函数,都是通过key找到与key对应的value然后返回其引用,不同的是:当key不存在时,operator[]用默认value与key构造键值对然后插入,返回该默认value,at()函数直接抛异常。
5. map中元素的修改
| 函数声明 | 功能简介 |
| pair<iterator,bool> insert ( const value_type& x ) | 在map中插入键值对x,注意x是一个键值对,返回值也是键值对:iterator代表新插入元素的位置,bool代表释放插入成功 |
| void erase ( iterator position ) | 删除position位置上的元素 |
| size_type erase ( const key_type& x ) | 删除键值为x的元素 |
| void erase ( iterator first, iterator last ) | 删除[first, last)区间中的元素 |
| void swap ( map<Key,T,Compare,Allocator>& mp ) | 交换两个map中的元素 |
| void clear ( ) | 将map中的元素清空 |
| iterator find ( const key_type& x ) | 在map中插入key为x的元素,找到返回该元素的位置的迭代器,否则返回end |
| const_iterator find ( const key_type& x ) const | 在map中插入key为x的元素,找到返回该元素的位置的const迭代器,否则返回cend |
| size_type count ( const key_type& x ) const | 返回key为x的键值在map中的个数,注意map中key是唯一的,因此该函数的返回值要么为0,要么为1,因此也可以用该函数来检测一个key是否在map中 |
6. map的使用举例
//map
void test_map1() {
//pair<iterator,bool> insert (const value_type& val);
//value_type pair<const key_type,mapped_type>
//pair的第一个参数应该是const修饰,但这里可以自动转换
//因为template<class U, class V> pair(const pair<U, V>& pr);
//当insert需要pair<const string, string>,而传入pair<string, string>时:
//编译器会调用这个模板构造函数,
//将pair<string, string>隐式转换为pair<const string, string>。
map<string, string> dict;
dict.insert(pair<string, string>("sort", "排序"));
dict.insert(pair<string, string>("insert", "插入"));
dict.insert(pair<const char*, const char*>("left", "左边"));
//template <class T1, class T2>
//pair<T1, T2> make_pair(T1 x, T2 y) {
// return (pair<T1, T2>(x, y));
//}
//因为上方的函数模版,实际中更常用下面的写法
dict.insert(make_pair("right", "右边"));//这里的T1和T2推衍出来是const char*
string s1("xxx"), s2("yyy");
dict.insert(make_pair(s1, s2));
//[]作用实例,注:先看test_map2()关于[]的解析
dict["erase"];//没有该元素,就是插入。
cout << dict["erase"] << endl;//查找,value是空字符串
dict["erase"] = "删除";//有,就是修改
cout << dict["erase"] << endl;
dict["test"] = "测试";//插入+修改
cout << dict["test"] << endl;
//map<string, string>::iterator it = dict.begin();
//while (it != dict.end()) {
// cout << (*it).first << ":" << (*it).second << endl;
// cout << it.operator->()->first << ":" << it->second << endl;
// //it.operator->()这里是函数调用,返回一个指针
// ++it;
//}
//for (auto& kv : dict) {
// //kv.first += 'x';//key不支持修改
// kv.second += 'x';
// cout << kv.first << ":" << kv.second << endl;
//}
}
void test_map2() {
string arr[] = { "苹果", "西瓜", "苹果", "西瓜", "苹果", "苹果", "西瓜", "苹果", "香蕉", "苹果", "香蕉" };
map<string, int> countMap;
for (auto& str : arr) {//遍历arr数组
//方法一
//auto ret = countMap.find(str);//查找countMap是否有该元素
//if (ret == countMap.end()) countMap.insert(make_pair(str, 1));//没有就插入
//else ret->second++;//有就++value
//方法二
countMap[str]++;
//[]里面传key,返回key对应value的引用
}
for (auto& kv : countMap)
cout << kv.first << ":" << kv.second << endl;
//mapped_type& operator[] (const key_type& k);
//(*((this->insert(make_pair(k,mapped_type()))).first)).
//pair<iterator,bool> insert (const value_type& val);
//要弄懂operator[]先要看insert返回值,关于insert返回值pair。
//插入成功 pair<新插入key所在节点的iterator,true>
//插入失败 pair<已存在key所在节点的iterator,false>
//[]可以改写为下方
//V& operator[](const K& key) {
// pair<iterator, bool> ret = insert(key, V());
// ret.firset->second;
//}
//取pair里的iterator就可以访问second
}
3.3 multiset
3.3.1 multiset的介绍
[翻译]:
- multiset是按照特定顺序存储元素的容器,其中元素是可以重复的。
- 在multiset中,元素的value也会识别它(因为multiset中本身存储的就是<value, value>组成的键值对,因此value本身就是key,key就是value,类型为T). multiset元素的值不能在容器中进行修改(因为元素总是const的),但可以从容器中插入或删除。
- 在内部,multiset中的元素总是按照其内部比较规则(类型比较)所指示的特定严格弱排序准则进行排序。
- multiset容器通过key访问单个元素的速度通常比unordered_multiset容器慢,但当使用迭代器遍历时会得到一个有序序列。
- multiset底层结构为二叉搜索树(红黑树)。
注意:
- multiset中再底层中存储的是<value, value>的键值对
- mtltiset的插入接口中只需要插入即可
- 与set的区别是,multiset中的元素可以重复,set是中value是唯一的
- 使用迭代器对multiset中的元素进行遍历,可以得到有序的序列
- multiset中的元素不能修改
- 在multiset中找某个元素,时间复杂度为$O(log_2 N)$
- multiset的作用:可以对元素进行排序
3.3.2 multiset的使用
此处只简单演示set与multiset的不同,其他接口接口与set相同
void test_set4() {
multiset<int> s;
s.insert(5);
s.insert(2);
s.insert(6);
s.insert(1);
s.insert(1);
s.insert(2);
s.insert(1);
s.insert(5);
s.insert(2);
multiset<int>::iterator it = s.begin();
while (it != s.end()) {
cout << *it << " ";
++it;
}
cout << endl;
for (auto e : s)
cout << e << " ";
cout << endl;
it = s.find(2);//有多个2,返回中序的第一个2
while (it != s.end()) {
cout << *it << " ";
++it;
}
cout << endl;
cout << s.count(1) << endl;//count更大的意义是为multiset设计
//返回一个范围的边界,该范围包括容器中等效于 val 的所有元素。
//[>=val, >val)
//auto ret = s.equal_range(2);//找到所有2。
//s.erase(ret.first, ret.second);//删除所有2
size_t n = s.erase(2);//该方式也可以删除所有2
cout << n << endl;//erase的返回值size_t可以知道删除了几个相同值
for (auto e : s)
cout << e << " ";
cout << endl;
}
3.4 multimap
3.4.1 multimap的介绍
翻译:
- Multimaps是关联式容器,它按照特定的顺序,存储由key和value映射成的键值对<key, value>,其中多个键值对之间的key是可以重复的。
- 在multimap中,通常按照key排序和唯一的标识元素,而映射的value存储与key关联的内容。key和value的类型可能不同,通过multimap内部的成员类型value_type组合在一起,value_type是组合key和value的键值对:typedef pair<const Key, T> value_type;
- 在内部,multimap中的元素总是通过其内部比较对象,按照指定的特定严格弱排序标准对key进行排序的。
- multimap通过key访问单个元素的速度通常比unordered_multimap容器慢,但是使用迭代器直接遍历multimap中的元素可以得到关于key有序的序列。
- multimap在底层用二叉搜索树(红黑树)来实现。
注意:multimap和map的唯一不同就是:map中的key是唯一的,而multimap中key是可以重复的。
3.4.2 multimap的使用
multimap中的接口可以参考map,功能都是类似的。
注意:
- multimap中的key是可以重复的。
- multimap中的元素默认将key按照小于来比较
- multimap中没有重载operator[]操作(同学们可思考下为什么?)。
- 使用时与map包含的头文件相同
3.5 在OJ中的使用
1. 692. 前K个高频单词 - 力扣(LeetCode)
class Solution {
public:
struct KvCom{
bool operator()(const pair<string, int>& kv1, const pair<string, int>& kv2) {
// return kv1.second > kv2.second;//不能只比较value
return kv1.second > kv2.second ||
(kv1.second == kv2.second && kv1.first < kv2.first);
}
};
vector<string> topKFrequent(vector<string>& words, int k) {
map<string, int> countMap;
for (auto& str : words)//先遍历vector并统计每个单词的次数
countMap[str]++;
//不能直接使用sort排序,因为sort要求随机访问迭代器
//但map的是双向迭代器,所以需要处理
//将map的数据以pair的形式插入到vector中,因为vector支持任意迭代器区间初始化
//但是,还不能使用sort直接排序。虽然pair支持比较,
//但pair的比较是first或second任意一个小就小
//所以需要自定义一个仿函数比较pair提供给sort
//map已经按字典顺序排序,但sort是不稳定排序(底层是快排),打乱了map的字典顺序
//所以仿函数不能只比较value
vector<pair<string, int>> kvV(countMap.begin(), countMap.end());
sort(kvV.begin(), kvV.end(), KvCom());
vector<string> v;
for (size_t i = 0; i < k; ++i)
v.push_back(kvV[i].first);
return v;
}
};
2. 349. 两个数组的交集 - 力扣(LeetCode)
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
//一个vector的数据插入到set中,用另一个vector的元素来查找不可行
//因为两个vector中都可能会有重复数据
//nums1 = [1,2,2,1], nums2 = [2,2]
//如果用nums2里的两个2去set中查找都会有,无法判断
//set可以排序+去重
set<int> map1(nums1.begin(), nums1.end());
set<int> map2(nums2.begin(), nums2.end());
//找交集 - 双指针
//set1:4 5 8 set2:4 8 9
//1.相同就是交集值,同时++
//2.不相同,小的++。因为排过序,小的不会和另一个map后面的值相同
//有一个结束就结束
//找差集
//1.相同,同时++
//2.不相同,小的++。小的是差集,因为排过序,小的不会和另一个map后面的值相同
//一个结束,另一个是差集
set<int>:: iterator it1 = map1.begin();
auto it2 = map2.begin();
vector<int> v;
while (it1 != map1.end() && it2 != map2.end()) {
if (*it1 < *it2)
++it1;
else if (*it2 < *it1)
++it2;
else{
v.push_back(*it1);
++it1;
++it2;
}
}
return v;
}
};
第四章:底层结构
前面对map/multimap/set/multiset进行了简单的介绍,在其文档介绍中发现,这几个容器有个共同点是:其底层都是按照二叉搜索树来实现的,但是二叉搜索树有其自身的缺陷,假如往树中插入的元素有序或者接近有序,二叉搜索树就会退化成单支树,时间复杂度会退化成O(N),因此map、set等关联式容器的底层结构是对二叉树进行了平衡处理,即采用平衡树来实现。
4.1 AVL 树
4.1.1 AVL树的概念
二叉搜索树虽可以缩短查找的效率,但如果数据有序或接近有序二叉搜索树将退化为单支树,查找元素相当于在顺序表中搜索元素,效率低下。因此,两位俄罗斯的数学家G.M.Adelson-Velskii和E.M.Landis在1962年发明了一种解决上述问题的方法:当向二叉搜索树中插入新结点后,如果能保证每个结点的左右子树高度之差的绝对值不超过1(需要对树中的结点进行调整),即可降低树的高度,从而减少平均搜索长度。
一棵AVL树或者是空树,或者是具有以下性质的二叉搜索树:
- 它的左右子树都是AVL树
- 左右子树高度之差(简称平衡因子)的绝对值不超过1(-1/0/1)

如果一棵二叉搜索树是高度平衡的,它就是AVL树。如果它有n个结点,其高度可保持在$O(log_2 n)$,搜索时间复杂度O($log_2 n$)。
4.1.2 AVL树节点的定义
template <class K, class V>
struct AVLTreeNode {
AVLTreeNode<K, V>* _left;
AVLTreeNode<K, V>* _right;
AVLTreeNode<K, V>* _parent;
pair<K, V> _kv;
int _bf;//平衡因子
AVLTreeNode(const pair<K, V>& kv)
:_left(nullptr)
, _right(nullptr)
, _parent(nullptr)
, _kv(kv)
, _bf(0) {
}
};
4.1.3 AVL树的插入
AVL树就是在二叉搜索树的基础上引入了平衡因子,因此AVL树也可以看成是二叉搜索树。那么
AVL树的插入过程可以分为两步:
- 按照二叉搜索树的方式插入新节点
- 调整节点的平衡因子
bool Insert(const T& data) {
// 1. 先按照二叉搜索树的规则将节点插入到AVL树中
// 2. 新节点插入后,AVL树的平衡性可能会遭到破坏,此时就需要更新平衡因子,并检测是否破坏了AVL树的平衡性
//pCur插入后,pParent的平衡因子一定需要调整,在插入之前,pParent
//的平衡因子分为三种情况:-1,0, 1, 分以下两种情况:
// 1. 如果pCur插入到pParent的左侧,只需给pParent的平衡因子-1即可
// 2. 如果pCur插入到pParent的右侧,只需给pParent的平衡因子+1即可
//此时:pParent的平衡因子可能有三种情况:0,正负1, 正负2
// 1. 如果pParent的平衡因子为0,说明插入之前pParent的平衡因子为正负1,
// 插入后被调整成0,此时满足AVL树的性质,插入成功
// 2. 如果pParent的平衡因子为正负1,说明插入前pParent的平衡因子一定为0,
// 插入后被更新成正负1,此时以pParent为根的树的高度增加,需要继续向上更新
// 3. 如果pParent的平衡因子为正负2,则pParent的平衡因子违反平衡树的性质,需要对其进行旋转处理
while (pParent) {
// 更新双亲的平衡因子
if (pCur == pParent->_pLeft)
pParent->_bf--;
else
pParent->_bf++;
// 更新后检测双亲的平衡因子
if (0 == pParent->_bf)
break;
else if (1 == pParent->_bf || -1 == pParent->_bf) {
// 插入前双亲的平衡因子是0,插入后双亲的平衡因为为1 或者 -1 ,说明以双亲为根的二叉树
// 的高度增加了一层,因此需要继续向上调整
pCur = pParent;
pParent = pCur->_pParent;
}
else {
// 双亲的平衡因子为正负2,违反了AVL树的平衡性,需要对以pParent
// 为根的树进行旋转处理
if (2 == pParent->_bf) {
// ...
}
else {
// ...
}
}
}
return true;
}
4.1.4 AVL树的旋转
如果在一棵原本是平衡的AVL树中插入一个新节点,可能造成不平衡,此时必须调整树的结构,使之平衡化。根据节点插入位置的不同,AVL树的旋转分为四种:
1. 新节点插入较高左子树的左侧---左左:右单旋

//上图在插入前,AVL树是平衡的,新节点插入到30的左子树(注意:此处不是左孩子)中,30左子树增加了一层,
//导致以60为根的二叉树不平衡,要让60平衡,只能将60左子树的高度减少一层,右子树增加一层,
//即将左子树往上提,这样60转下来,因为60比30大,只能将其放在30的右子树,而如果30有右子树,
//右子树根的值一定大于30,小于60,只能将其放在60的左子树,旋转完成后,更新节点的平衡因子即可。
//在旋转过程中,有以下几种情况需要考虑:
//1. 30节点的右孩子可能存在,也可能不存在
//2. 60可能是根节点,也可能是子树
// 如果是根节点,旋转完成后,要更新根节点
// 如果是子树,可能是某个节点的左子树,也可能是右子树
void RotateR(Node* parent) {
Node* subL = parent->_left, * subLR = subL->_right, * parentParent = parent->_parent;
//旋转
parent->_left = subLR;
subL->_right = parent;
//处理各节点的父节点
parent->_parent = subL;
if (subLR) subLR->_parent = parent;
//处理根节点
if (_root == parent) {
_root = subL;
subL->_parent = nullptr;
}
else {
if (parent == parentParent->_left) parentParent->_left = subL;
else parentParent->_right = subL;
subL->_parent = parentParent;
}
parent->_bf = subL->_bf = 0;
}
2. 新节点插入较高右子树的右侧---右右:左单旋

//左单旋场景,是指新节点插入在较高右子树的右侧,导致右子树的高度比左子树高超过1
//左单旋通过将较高的右子树提升为新的根节点,同时调整其左子树的位置,使得左右子树的高度差减小
void RotateL(Node* parent) {
//parent是平衡因子为2的节点
Node* subR = parent->_right;
Node* subRL = subR->_left;
Node* parentParent = parent->_parent;//parent不一定是整棵树的根
//旋转完后,subR是子树的根,还需要处理subR的parent
//旋转
parent->_right = subRL;
subR->_left = parent;
//上方还未处理完,根节点没有确定,各节点的parent还未更新
parent->_parent = subR;
if (subRL) subRL->_parent = parent;
//处理根节点
if (_root == parent) { //parent是整棵树的根
_root = subR;
subR->_parent = nullptr;
}
else { //parent不一定是整棵树的根,旋转完后,还需要处理subR的parent
if (parent == parentParent->_left) parentParent->_left = subR;
else parentParent->_right = subR;
subR->_parent = parentParent;
}
parent->_bf = subR->_bf = 0;//处理平衡因子
}
3. 新节点插入较高左子树的右侧---左右:先左单旋再右单旋

将双旋变成单旋后再旋转,即:先对30进行左单旋,然后再对90进行右单旋,旋转完成后再考虑平衡因子的更新。
// 旋转之前,60的平衡因子可能是-1/0/1,旋转完成之后,根据情况对其他节点的平衡因子进行调整
void RotateLR(Node* parent) {
Node* subL = parent->_left;
Node* subLR = subL->_right;
// 旋转之前,保存pSubLR的平衡因子,旋转完成之后,
//需要根据该平衡因子来调整其他节点的平衡因子
int bf = subLR->_bf;
RotateL(subL);
RotateR(parent);
if (bf == 0)
parent->_bf = subL->_bf = subLR->_bf = 0;
else if (bf == -1) {
subL->_bf = subLR->_bf = 0;
parent->_bf = 1;
}
else if (bf == 1) {
parent->_bf = subLR->_bf = 0;
subL->_bf = -1;
}
else
assert(false);
}
4. 新节点插入较高右子树的左侧---右左:先右单旋再左单旋

//新节点插入较高右子树的左侧---右左:先右单旋再左单旋
void RotateRL(Node* parent) {
Node* subR = parent->_right;
Node* subRL = subR->_left;
int bf = subRL->_bf;//保存subRL节点的平衡因子,用于在旋转后正确更新相关节点的平衡因子。
//新增节点可能为subRL 或 subRL的左子树 或subRL的右子树。
//这三种不同的情况会导致旋转完成后,parent、subR、subRL的平衡因子不同
RotateR(subR);
RotateL(parent);
if (bf == 0)
parent->_bf = subR->_bf = subRL->_bf = 0;//subRL自己是新增
else if (bf == -1) { //在subRL的左子树新增
parent->_bf = subRL->_bf = 0;
subR->_bf = 1;
}
else if (bf == 1) { //在subRL的右子树新增
subR->_bf = subRL->_bf = 0;
parent->_bf = -1;
}
else
assert(false);
}
总结:
假如以pParent为根的子树不平衡,即pParent的平衡因子为2或者-2,分以下情况考虑
1. pParent的平衡因子为2,说明pParent的右子树高,设pParent的右子树的根为pSubR
- 当pSubR的平衡因子为1时,执行左单旋
- 当pSubR的平衡因子为-1时,执行右左双旋
2. pParent的平衡因子为-2,说明pParent的左子树高,设pParent的左子树的根为pSubL
- 当pSubL的平衡因子为-1是,执行右单旋
- 当pSubL的平衡因子为1时,执行左右双旋
旋转完成后,原pParent为根的子树个高度降低,已经平衡,不需要再向上更新。
4.1.5 AVL树的验证
AVL树是在二叉搜索树的基础上加入了平衡性的限制,因此要验证AVL树,可以分两步:
1. 验证其为二叉搜索树
如果中序遍历可得到一个有序的序列,就说明为二叉搜索树
2. 验证其为平衡树
每个节点子树高度差的绝对值不超过1(注意节点中如果没有平衡因子)
节点的平衡因子是否计算正确
int _Height(PNode pRoot);
bool _IsBalanceTree(PNode pRoot) {
// 空树也是AVL树
if (nullptr == pRoot) return true;
// 计算pRoot节点的平衡因子:即pRoot左右子树的高度差
int leftHeight = _Height(pRoot->_pLeft);
int rightHeight = _Height(pRoot->_pRight);
int diff = rightHeight - leftHeight;
// 如果计算出的平衡因子与pRoot的平衡因子不相等,或者
// pRoot平衡因子的绝对值超过1,则一定不是AVL树
if (diff != pRoot->_bf || (diff > 1 || diff < -1))
return false;
// pRoot的左和右如果都是AVL树,则该树一定是AVL树
return _IsBalanceTree(pRoot->_pLeft) && _IsBalanceTree(pRoot -
> _pRight);
}
3. 验证用例
结合上述代码按照以下的数据次序,自己动手画AVL树的创建过程,验证代码是否有漏洞。
特殊场景2 {4, 2, 6, 1, 3, 5, 15, 7, 16, 14}

4.1.6 AVL树的删除(了解)
因为AVL树也是二叉搜索树,可按照二叉搜索树的方式将节点删除,然后再更新平衡因子,只不过与删除不同的时,删除节点后的平衡因子更新,最差情况下一直要调整到根节点的位置。具体实现可参考《算法导论》或《数据结构-用面向对象方法与C++描述》殷人昆版。
4.1.7 AVL树的性能
AVL树是一棵绝对平衡的二叉搜索树,其要求每个节点的左右子树高度差的绝对值都不超过1,这样可以保证查询时高效的时间复杂度,即$log_2 (N)$。但是如果要对AVL树做一些结构修改的操作,性能非常低下,比如:插入时要维护其绝对平衡,旋转的次数比较多,更差的是在删除时,有可能一直要让旋转持续到根的位置。因此:如果需要一种查询高效且有序的数据结构,而且数据的个数为静态的(即不会改变),可以考虑AVL树,但一个结构经常修改,就不太适合。
AVLTree.h
#pragma once
template <class K, class V>
struct AVLTreeNode {
AVLTreeNode<K, V>* _left;
AVLTreeNode<K, V>* _right;
AVLTreeNode<K, V>* _parent;
pair<K, V> _kv;
int _bf;//平衡因子
AVLTreeNode(const pair<K, V>& kv)
:_left(nullptr)
, _right(nullptr)
, _parent(nullptr)
, _kv(kv)
, _bf(0) {
}
};
template <class K, class V>
struct AVLTree {
typedef AVLTreeNode<K, V> Node;
public:
bool Insert(const pair<K, V>& kv) {
if (_root == nullptr) {
_root = new Node(kv);
return true;
}
Node* parent = nullptr, * cur = _root;
while (cur) {
if (kv.first > cur->_kv.first) {
parent = cur;
cur = cur->_right;
}
else if (kv.first < cur->_kv.first) {
parent = cur;
cur = cur->_left;
}
else
return false;
}
cur = new Node(kv);
if (kv.first > parent->_kv.first) {
parent->_right = cur;
cur->_parent = parent;
}
else {
parent->_left = cur;
cur->_parent = parent;
}
//调整平衡
//新增节点可能会影响祖先,取决于子树的高度是否变化
//1.如果子树高度[不变],就[不会]继续往上影响祖先
//2.如果子树高度[变化],就[会]继续往上影响祖先
//新增节点在左子树,父节点_bf--;新增节点在右子树,父节点_bf++。
//是否要继续往上更新,分3种情况
//1.父节点_bf更新后 == 0,父节点的子树高度不变,不用继续往上更新,插入结束
// ps:在插入之前,父节点_bf == -1 或 1,一边高一边低,新插入节点填上低的那边
//2.父节点_bf更新后 == 1 或 -1,父节点的子树高度变化,必须继续往上更新
// ps:在插入之前,父节点_bf == 0,两边一样高,插入导致高度变化
//3.父节点_bf更新后 == 2 或 -2,父节点的子树违反规则,需要调整
//往上查看最高需要到根,所以cur需要指向根,此时parent就会空,所以parent不为空就继续
while (parent) {
//更新父节点平衡因子
if (cur == parent->_left) parent->_bf--;
else parent->_bf++;
//查看父节点平衡因子,以此判断是否需要调整
if (parent->_bf == 0) break;
else if (parent->_bf == 1 || parent->_bf == -1) {
cur = parent;
parent = parent->_parent;
}
else if (parent->_bf == 2 || parent->_bf == -2) {
//旋转
//1.保证左右均衡
//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)
RotateRL(parent);
else if (parent->_bf == -2 && cur->_bf == 1)
RotateLR(parent);
//旋转后不需要再往上查看,因为新插入节点增加了高度,但旋转又减低了高度
break;
}
else //以防平衡因子超过2,不是AVLTree,直接报错
assert(false);
}
return true;
}
//左单旋
//解释1:
//假设平衡因子是2的节点为A,它的右子节点为B
//将A->right指向B->left,在将B->left指向A
//解释2:
//如果一个节点的父节点平衡因子是2,将它的左子结点给其父节点的右子节点
//再将其父节点当做自己的左子结点
//左单旋场景,是指新节点插入在较高右子树的右侧,导致右子树的高度比左子树高超过1
//左单旋通过将较高的右子树提升为新的根节点,同时调整其左子树的位置,使得左右子树的高度差减小
void RotateL(Node* parent) {
//parent是平衡因子为2的节点
Node* subR = parent->_right;
Node* subRL = subR->_left;
Node* parentParent = parent->_parent;//parent不一定是整棵树的根
//旋转完后,subR是子树的根,还需要处理subR的parent
//旋转
parent->_right = subRL;
subR->_left = parent;
//上方还未处理完,根节点没有确定,各节点的parent还未更新
parent->_parent = subR;
if (subRL) subRL->_parent = parent;
//处理根节点
if (_root == parent) { //parent是整棵树的根
_root = subR;
subR->_parent = nullptr;
}
else { //parent不一定是整棵树的根,旋转完后,还需要处理subR的parent
if (parent == parentParent->_left) parentParent->_left = subR;
else parentParent->_right = subR;
subR->_parent = parentParent;
}
parent->_bf = subR->_bf = 0;//处理平衡因子
}
void RotateR(Node* parent) {
Node* subL = parent->_left, * subLR = subL->_right, * parentParent = parent->_parent;
//旋转
parent->_left = subLR;
subL->_right = parent;
//处理各节点的父节点
parent->_parent = subL;
if (subLR) subLR->_parent = parent;
//处理根节点
if (_root == parent) {
_root = subL;
subL->_parent = nullptr;
}
else {
if (parent == parentParent->_left) parentParent->_left = subL;
else parentParent->_right = subL;
subL->_parent = parentParent;
}
parent->_bf = subL->_bf = 0;
}
//新节点插入较高右子树的左侧---右左:先右单旋再左单旋
void RotateRL(Node* parent) {
Node* subR = parent->_right;
Node* subRL = subR->_left;
int bf = subRL->_bf;//保存subRL节点的平衡因子,用于在旋转后正确更新相关节点的平衡因子。
//新增节点可能为subRL 或 subRL的左子树 或subRL的右子树。
//这三种不同的情况会导致旋转完成后,parent、subR、subRL的平衡因子不同
RotateR(subR);
RotateL(parent);
if (bf == 0)
parent->_bf = subR->_bf = subRL->_bf = 0;//subRL自己是新增
else if (bf == -1) { //在subRL的左子树新增
parent->_bf = subRL->_bf = 0;
subR->_bf = 1;
}
else if (bf == 1) { //在subRL的右子树新增
subR->_bf = subRL->_bf = 0;
parent->_bf = -1;
}
else
assert(false);
}
//新节点插入较高左子树的右侧---左右:先左单旋再右单旋
void RotateLR(Node* parent) {
Node* subL = parent->_left;
Node* subLR = subL->_right;
int bf = subLR->_bf;
RotateL(subL);
RotateR(parent);
if (bf == 0)
parent->_bf = subL->_bf = subLR->_bf = 0;
else if (bf == -1) {
subL->_bf = subLR->_bf = 0;
parent->_bf = 1;
}
else if (bf == 1) {
parent->_bf = subLR->_bf = 0;
subL->_bf = -1;
}
else
assert(false);
}
Node* Find(const K& key) {
Node* cur = _root;
while (cur) {
if (key > _root->_kv.first) cur = cur->_right;
else if (key < _root->_kv.first) cur = cur->_left;
else return cur;
}
return nullptr;
}
void InOrder() {
_InOrder(_root);
cout << endl;
}
bool IsBalance() { return _IsBalance(_root); }
int Height() { return _Height(_root); }
size_t Size() { return _Size(_root); }
private:
Node* _root = nullptr;
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 leftHeight = _Height(root->_left);
int rightHeight = _Height(root->_right);
return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
}
bool _IsBalance(Node* root) {
if (root == nullptr) return true;
int leftHeight = _Height(root->_left);
int rightHeight = _Height(root->_right);
//验证当前节点的平衡因子是否正确,通过实际计算得到的左右子树高度差去验证
//如果不相等,说明平衡因子计算或维护有误
if (rightHeight - leftHeight != root->_bf) {
cout << root->_kv.first << "平衡因子异常" << endl;
return false;
}
return abs(rightHeight - leftHeight) < 2 //当前节点左右子树高度
&& _IsBalance(root->_left) //继续检查其左子树的左右子树高度
&& _IsBalance(root->_right);
}
size_t _Size(Node* root) {
if (root == nullptr) return 0;
return _Size(root->_left) + _Size(root->_right) + 1;
}
};
AVLTree.cpp
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <map>
#include <assert.h>
#include<vector>
using namespace std;
#include "AVLTree.h"
int main() {
multimap<string, string> dict;//全部可以插入
dict.insert(make_pair("left", "左边"));
dict.insert(make_pair("left", "剩余"));
dict.insert(make_pair("left", "左边"));
//map<string, string> dict;//只能插入第一个 "左边"
//dict.insert(make_pair("left", "左边"));
//dict.insert(make_pair("left", "剩余"));//修改value要使用[]
for (auto& kv : dict)
cout << kv.first << ":" << kv.second << endl;
return 0;
}
//测试AVLTree
int main() {
//int a[] = { 16, 3, 7, 11, 9, 26, 18, 14, 15 };
int a[] = { 4, 2, 6, 1, 3, 5, 15, 7, 16, 14 };//涉及双旋
AVLTree<int, int> t;
for (auto e : a)
t.Insert(make_pair(e, e));//value可以是任意数据,这里value和key相同,只是为了方便演示。
t.InOrder();
cout << t.IsBalance() << endl;
return 0;
}
//进一步测试AVLTree
int main() {
const int N = 1000000;
vector<int> v;
v.reserve(N);
srand((unsigned int)time(0));
for (size_t i = 0; i < N; i++)
v.push_back(rand() + i);
size_t begin2 = clock();
AVLTree<int, int> t;
for (auto e : v)
t.Insert(make_pair(e, e));
size_t end2 = clock();
cout << t.IsBalance() << endl;
cout << t.Height() << endl;
cout << t.Size() << endl;
size_t begin1 = clock();
for (auto e : v)
t.Find(e);
size_t end1 = clock();
cout << "Find:" << end1 - begin1 << endl;
cout << "Insert:" << end2 - begin2 << endl;
//如果有问题可以用下面的方式调试
const int N = 20;
vector<int> v;
v.reserve(N);
//srand((unsigned int)time(0));//屏蔽这行只生成一次随机数
for (size_t i = 0; i < N; i++) {
v.push_back(rand());
cout << v.back() << endl;
}
AVLTree<int, int> t;
for (auto e : v) {
if (e == 14604)
int x = 0;//这样没意义,只是为了打断点,空语句不能打断点
t.Insert(make_pair(e, e));
cout << "Insert:" << e << "->" << t.IsBalance() << endl;
}
cout << t.IsBalance() << endl;
return 0;
}
4.2 红黑树
4.2.1 红黑树的概念
红黑树,是一种二叉搜索树,但在每个结点上增加一个存储位表示结点的颜色,可以是Red或Black。 通过对任何一条从根到叶子的路径上各个结点着色方式的限制,红黑树确保没有一条路径会比其他路径长出俩倍,因而是接近平衡的。

4.2.2 红黑树的性质
- 每个结点不是红色就是黑色
- 根节点是黑色的
- 如果一个节点是红色的,则它的两个孩子结点是黑色的
- 对于每个结点,从该结点到其所有后代叶结点的简单路径上,均 包含相同数目的黑色结点
- 每个叶子结点都是黑色的(此处的叶子结点指的是空结点)
思考:为什么满足上面的性质,红黑树就能保证:其最长路径中节点个数不会超过最短路径节点个数的两倍?
最短路径:全黑节点
最长路径:红黑交替(因规则3,红色不能连续)
设黑高为h,则:
最短路径长度 = h(全黑)
最长路径长度 ≤ 2h(红黑交替时)
因此最长路径 ≤ 2 × 最短路径
4.2.3 红黑树节点的定义
// 节点的颜色
enum Color { RED, BLACK };
// 红黑树节点的定义
template<class ValueType>
struct RBTreeNode {
RBTreeNode(const ValueType& data = ValueType(),Color color = RED)
: _pLeft(nullptr), _pRight(nullptr), _pParent(nullptr)
, _data(data), _color(color) {
}
RBTreeNode<ValueType>* _pLeft;//节点的左孩子
RBTreeNode<ValueType>* _pRight;//节点的右孩子
RBTreeNode<ValueType>* _pParent;//节点的双亲(红黑树需要旋转,为了实现简单给出该字段)
ValueType _data;//节点的值域
Color _color;//节点的颜色
};
4.2.4 红黑树的插入操作
红黑树是在二叉搜索树的基础上加上其平衡限制条件,因此红黑树的插入可分为两步:
2. 检测新节点插入后,红黑树的性质是否造到破坏
因为新节点的默认颜色是红色,因为:如果其双亲节点的颜色是黑色,没有违反红黑树任何性质,则不需要调整;但当新插入节点的双亲节点颜色为红色时,就违反了性质三不能有连在一起的红色节点,此时需要对红黑树分情况来讨论:
约定:cur为当前节点,p为父节点,g为祖父节点,u为叔叔节点
情况一: cur为红,p为红,g为黑,u存在且为红

情况二: cur为红,p为红,g为黑,u不存在/u存在且为黑

情况三: cur为红,p为红,g为黑,u不存在/u存在且为黑

4.2.5 红黑树的验证
红黑树的检测分为两步:
- 检测其是否满足二叉搜索树(中序遍历是否为有序序列)
- 检测其是否满足红黑树的性质
4.2.6 红黑树的删除
不做讲解,有兴趣可参考:《算法导论》或者《STL源码剖析》
4.2.7 红黑树与AVL树的比较
红黑树和AVL树都是高效的平衡二叉树,增删改查的时间复杂度都是O($log_2 N$),红黑树不追求绝对平衡,其只需保证最长路径不超过最短路径的2倍,相对而言,降低了插入和旋转的次数,所以在经常进行增删的结构中性能比AVL树更优,而且红黑树实现比较简单,所以实际运用中红黑树更多。
RBTree.h
#pragma once
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 RBTree {
typedef RBTreeNode<K, V> Node;
public:
bool Insert(const pair<K, V>& kv) {
if (_root == nullptr) { //如果插入节点是根
_root = new Node(kv);
_root->_col = BLACK;
return true;
}
//不是根,找插入位置。记录插入节点的父节点方便链接
Node* parent = nullptr, * cur = _root;
while (cur) {
if (kv.first > cur->_kv.first) {
parent = cur;
cur = cur->_right;
}
else if (kv.first < cur->_kv.first) {
parent = cur;
cur = cur->_left;
}
else
return false;
}
//新增黑色节点会影响所有路径
//新增红色节点只会影响父节点
cur = new Node(kv);
cur->_col = RED;
//插入节点链接在其父节点的左或右
if (kv.first > parent->_kv.first) {
parent->_right = cur;
cur->_parent = parent;
}
else {
parent->_left = cur;
cur->_parent = parent;
}
//检查是否需要变色
//cur的父节点为空(即根节点),或其父节点不是红色就不用更新
while (parent && parent->_col == RED) {
Node* grandfather = parent->_parent;
if (parent == grandfather->_left) { //通过g找到u。p为g的左孩子
Node* uncle = grandfather->_right;
//u存在且为红(cur为红,p为红,g为黑)
if (uncle && uncle->_col == RED) { //u存在且为红
parent->_col = uncle->_col = BLACK;
grandfather->_col = RED;
//继续往上更新,去找上一个红节点
cur = grandfather;//grandfather有可能为根,所以父节点可能不存在,所以需要在循环条件中判断
parent = cur->_parent;
}
else { //u不存在或u为黑(cur为红,p为红,g为黑)
//p为g的左孩子,cur为p的左孩子,则进行右单旋转。(这里p已经是g的左)
if (cur == parent->_left) {
RotateR(grandfather);
parent->_col = BLACK;
grandfather->_col = RED;
}
else { //p为g的左孩子,cur为p的右孩子。(这里p已经是g的左)
RotateL(parent);
RotateR(grandfather);
cur->_col = BLACK;
grandfather->_col = RED;
}
break;
}
}
else { //parent == grandfather->_right;
Node* uncle = grandfather->_left;
if (uncle && uncle->_col == RED) {
parent->_col = uncle->_col = BLACK;
grandfather->_col = RED;
cur = grandfather;
parent = cur->_parent;
}
else {
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;
}
}
}
//根节点必须为黑,所以不用在上面的过程中考虑grandfather为根时怎么变色的问题
_root->_col = BLACK;
return true;
}
void RotateL(Node* parent) {
//parent是平衡因子为2的节点
Node* subR = parent->_right;
Node* subRL = subR->_left;
Node* parentParent = parent->_parent;//parent不一定是整棵树的根
//旋转完后,subR是子树的根,还需要处理subR的parent
//旋转
parent->_right = subRL;
subR->_left = parent;
//上方还未处理完,根节点没有确定,各节点的parent还未更新
parent->_parent = subR;
if (subRL) subRL->_parent = parent;
//处理根节点
if (_root == parent) { //parent是整棵树的根
_root = subR;
subR->_parent = nullptr;
}
else { //parent不一定是整棵树的根,旋转完后,还需要处理subR的parent
if (parent == parentParent->_left) parentParent->_left = subR;
else parentParent->_right = subR;
subR->_parent = parentParent;
}
}
void RotateR(Node* parent) {
Node* subL = parent->_left, * subLR = subL->_right, * parentParent = parent->_parent;
//旋转
parent->_left = subLR;
subL->_right = parent;
//处理各节点的父节点
parent->_parent = subL;
if (subLR) subLR->_parent = parent;
//处理根节点
if (_root == parent) {
_root = subL;
subL->_parent = nullptr;
}
else {
if (parent == parentParent->_left) parentParent->_left = subL;
else parentParent->_right = subL;
subL->_parent = parentParent;
}
}
Node* Find(const K& key) {
Node* cur = _root;
while (cur) {
if (key > _root->_kv.first) cur = cur->_right;
else if (key < _root->_kv.first) cur = cur->_left;
else return cur;
}
return nullptr;
}
void InOrder() {
_InOrder(_root);
cout << endl;
}
bool IsBalance() {
if (_root == nullptr) return true;
if (_root->_col == RED) return false;
int blacknum = 0;//根节点到当前节点的黑色节点数量
//blacknum只能传值,不能传引用。引用求得是整棵树所有黑色节点
//将最左路径节点作为参考值传入Check和其他路径比较
int refVal = 0;
Node* cur = _root;
while (cur) {
if (cur->_col == BLACK) ++refVal;
cur = cur->_left;
}
return Check(_root, blacknum, refVal);
}
int Height() { return _Height(_root); }
size_t Size() { return _Size(_root); }
private:
Node* _root = nullptr;
void _InOrder(Node* root) {
if (root == nullptr)
return;
_InOrder(root->_left);
cout << root->_kv.first << " ";
_InOrder(root->_right);
}
bool Check(Node* root, int blacknum, const int refVal) {
if (root == nullptr) {
//cout << blacknum << endl;
//走到空意味着求出了一条路径的黑色节点数量
if (refVal != blacknum) {
cout << "存在黑色节点数量不相等的路径" << endl;
return false;
}
return true;
}
if (root->_col == RED && root->_parent->_col == RED) {
cout << "有连续的红色节点" << endl;
return false;
}
if (root->_col == BLACK) ++blacknum;
return Check(root->_left, blacknum, refVal)
&& Check(root->_right, blacknum, refVal);
}
int _Height(Node* root) {
if (root == nullptr) return 0;
int leftHeight = _Height(root->_left);
int rightHeight = _Height(root->_right);
return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
}
size_t _Size(Node* root) {
if (root == nullptr) return 0;
return _Size(root->_left) + _Size(root->_right) + 1;
}
};
RBTree.cpp
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <string>
using namespace std;
#include "RBTree.h"
//测试红黑树
int main() {
//int a[] = { 16, 3, 7, 11, 9, 26, 18, 14, 15 };
int a[] = { 4, 2, 6, 1, 3, 5, 15, 7, 16, 14 };//涉及双旋
RBTree<int, int> t;
for (auto e : a)
t.Insert(make_pair(e, e));
t.InOrder();
cout << t.IsBalance() << endl;
return 0;
}
//进一步测试红黑树
int main() {
const int N = 1000000;
vector<int> v;
v.reserve(N);
srand((unsigned int)time(0));
for (size_t i = 0; i < N; i++)
v.push_back(rand() + i);
size_t begin2 = clock();
RBTree<int, int> t;
for (auto e : v)
t.Insert(make_pair(e, e));
size_t end2 = clock();
size_t begin1 = clock();
for (auto e : v)
t.Find(e);
size_t end1 = clock();
cout << "是否为红黑树:" << t.IsBalance() << endl;
//cout << "Insert:" << end1 - begin1 << endl;
cout << "Height:" << t.Height() << endl;
cout << "Size:" << t.Size() << endl;
cout << "Find Time:" << end1 - begin1 << endl;
cout << "Insert Time:" << end2 - begin2 << endl;
return 0;
}
#include "MySet.h"
#include "MyMap.h"
void test_set() {
bit::set<int> s;
s.Insert(4);
s.Insert(1);
s.Insert(2);
s.Insert(3);
s.Insert(2);
s.Insert(0);
s.Insert(10);
s.Insert(5);
bit::set<int>::iterator it = s.begin();
while (it != s.end()) {
cout << *it << " ";
++it;
}
cout << endl;
for (auto e : s)
cout << e << " ";
cout << endl;
}
void test_map() {
bit::map<string, string> dict;
dict.Insert(make_pair("sort", "排序"));
dict.Insert(make_pair("sort", "xx"));
dict.Insert(make_pair("left", "左边"));
dict.Insert(make_pair("right", "右边"));
bit::map<string, string>::iterator it = dict.begin();
while (it != dict.end()) {
//it->first += "y";
it->second += "y";
cout << it->first << ":" << it->second << endl;
++it;
}
string arr[] = { "苹果", "西瓜", "苹果", "西瓜", "苹果", "苹果", "西瓜", "苹果", "香蕉", "苹果", "香蕉" };
bit::map<string, int> countMap;
for (auto& e : arr)
countMap[e]++;
for (auto& kv : countMap)
cout << kv.first << ":" << kv.second << endl;
}
int main() {
//test_set();
test_map();
return 0;
}
4.3 红黑树模拟实现STL中的map与set
4.3.1 改造红黑树
RBTree.h
#pragma once
enum Color {
RED,
BLACK
};
template <class T>
struct RBTreeNode {
RBTreeNode<T>* _left;
RBTreeNode<T>* _right;
RBTreeNode<T>* _parent;
T _data;
Color _col;
RBTreeNode(const T& data)
:_left(nullptr)
, _right(nullptr)
, _parent(nullptr)
, _data(data)
, _col(RED) {
}
};
//迭代器
template <class T, class Ref, class Ptr>
struct __TreeIterator {
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; }
Self& operator++() {
//it.begin()返回的是中序的第一个节点
//++就是中序遍历的顺序
//1. it的右不为空,下一个就是其右子树的最左节点
//2. it的右为空,往上找在其父左的节点(A),A的父节点就是下一个
//沿着该节点的路径往上面找孩子是其父的左的祖先节点
//_node不用担心为空,因为正常使用迭代器它不会为空
if (_node->_right) { //右不为空。
Node* cur = _node->_right;
while (cur->_left) cur = cur->_left;
_node = cur;
}
else { //右为空
Node* cur = _node;
Node* parent = cur->_parent;
while (parent && cur == parent->_right) { //cur是其父的右就继续,不是才停下来
cur = parent;
parent = parent->_parent;
}
_node = parent;
}
return *this;
}
Self& operator--() {
//++是中序 左 根 右,所以--就是中序倒过来右 根 左
//1.左不为空,左子树的最右节点
//2.左为空,沿着该节点的路径往上面找孩子是其父的右的那个祖先
if (_node->_left) {
Node* cur = _node->_left;
while (cur->_right) cur = cur->_right;
_node = cur;
}
else {
Node* cur = _node;
Node* parent = cur->_parent;
while (parent && cur == parent->_left) {
cur = parent;
parent = parent->_parent;
}
_node = parent;
}
return *this;
}
bool operator!=(const Self& s) { return _node != s._node; }
bool operator==(const Self& s) { return _node == s._node; }
};
//第二个T实际存储的数据类型,节点中 _data 的具体类型(set存K,map存pair<K, V>)。
//class KeyOfT是为了取T _data 里的key(主要是针对map,因为map的T是pair<K, T>)
//set -> RBTree<K, K, SetKeyOfT> _t;
//map -> RBTree<K, pair<const K, T>, MapKeyOfT> _t;
//红黑树提供一个通用的键值提取接口(KeyOfT),而set和map自行定义如何提取键值
//对于map来说,KeyOfT只是取模版参数T(pair<const K, T>)中K的值(但没有类型)
template <class K, class T, class KeyOfT>
struct RBTree {
typedef RBTreeNode<T> Node;
public:
typedef __TreeIterator<T, T&, T*> iterator;
typedef __TreeIterator<T, const T&, const T*> const_iterator;
iterator begin() {
Node* cur = _root;
while (cur && cur->_left) cur = cur->_left;
return iterator(cur);
}
iterator end() { return iterator(nullptr); }
const_iterator begin() const {
Node* cur = _root;
while (cur && cur->_left) cur = cur->_left;
return const_iterator(cur);
}
const_iterator end() const { return const_iterator(nullptr); }
//pair<iterator, bool> Insert(const T& data) {
//set迭代器都是const迭代器,所以传Node*初始化const迭代器
//迭代器都是用Node*初始化的,所以传Node*可行
pair<Node*, bool> Insert(const T& data) {
if (_root == nullptr) { //如果插入节点是根
_root = new Node(data);
_root->_col = BLACK;
return make_pair(_root, true);
}
//不是根,找插入位置。记录插入节点的父节点方便链接
Node* parent = nullptr, * cur = _root;
KeyOfT kot;
//data是什么并不确定,KeyOfT是个仿函数类模板,可以取data里面的key
while (cur) {
if (kot(data) > kot(cur->_data)) {
parent = cur;
cur = cur->_right;
}
else if (kot(data) < kot(cur->_data)) {
parent = cur;
cur = cur->_left;
}
else
return make_pair(cur, false);
//insert 返回值规范
//first: 指向已插入或已存在元素的迭代器
//second: 是否插入成功(true=新插入,false=已存在)
//所以插入失败不能返回空,要返回已存在key的位置
}
//新增黑色节点会影响所有路径
//新增红色节点只会影响父节点
cur = new Node(data);
Node* newnode = cur;//记录新插入节点是为了最后返回
cur->_col = RED;
//插入节点链接在其父节点的左或右
if (kot(data) > kot(parent->_data)) {
parent->_right = cur;
cur->_parent = parent;
}
else {
parent->_left = cur;
cur->_parent = parent;
}
//检查是否需要变色
//cur的父节点为空(即根节点),或其父节点不是红色就不用更新
while (parent && parent->_col == RED) {
Node* grandfather = parent->_parent;
if (parent == grandfather->_left) { //通过g找到u。p为g的左孩子
Node* uncle = grandfather->_right;
//u存在且为红(cur为红,p为红,g为黑)
if (uncle && uncle->_col == RED) { //u存在且为红
parent->_col = uncle->_col = BLACK;
grandfather->_col = RED;
//继续往上更新,去找上一个红节点
cur = grandfather;//grandfather有可能为根,所以父节点可能不存在,所以需要在循环条件中判断
parent = cur->_parent;
}
else { //u不存在或u为黑(cur为红,p为红,g为黑)
//p为g的左孩子,cur为p的左孩子,则进行右单旋转。(这里p已经是g的左)
if (cur == parent->_left) {
RotateR(grandfather);
parent->_col = BLACK;
grandfather->_col = RED;
}
else { //p为g的左孩子,cur为p的右孩子。(这里p已经是g的左)
RotateL(parent);
RotateR(grandfather);
cur->_col = BLACK;
grandfather->_col = RED;
}
break;
}
}
else { //parent == grandfather->_right;
Node* uncle = grandfather->_left;
if (uncle && uncle->_col == RED) {
parent->_col = uncle->_col = BLACK;
grandfather->_col = RED;
cur = grandfather;
parent = cur->_parent;
}
else {
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;
}
}
}
//根节点必须为黑,所以不用在上面的过程中考虑grandfather为根时怎么变色的问题
_root->_col = BLACK;
return make_pair(newnode, true);//返回新插入节点
}
void RotateL(Node* parent) {
//parent是平衡因子为2的节点
Node* subR = parent->_right;
Node* subRL = subR->_left;
Node* parentParent = parent->_parent;//parent不一定是整棵树的根
//旋转完后,subR是子树的根,还需要处理subR的parent
//旋转
parent->_right = subRL;
subR->_left = parent;
//上方还未处理完,根节点没有确定,各节点的parent还未更新
parent->_parent = subR;
if (subRL) subRL->_parent = parent;
//处理根节点
if (_root == parent) { //parent是整棵树的根
_root = subR;
subR->_parent = nullptr;
}
else { //parent不一定是整棵树的根,旋转完后,还需要处理subR的parent
if (parent == parentParent->_left) parentParent->_left = subR;
else parentParent->_right = subR;
subR->_parent = parentParent;
}
}
void RotateR(Node* parent) {
Node* subL = parent->_left, * subLR = subL->_right, * parentParent = parent->_parent;
//旋转
parent->_left = subLR;
subL->_right = parent;
//处理各节点的父节点
parent->_parent = subL;
if (subLR) subLR->_parent = parent;
//处理根节点
if (_root == parent) {
_root = subL;
subL->_parent = nullptr;
}
else {
if (parent == parentParent->_left) parentParent->_left = subL;
else parentParent->_right = subL;
subL->_parent = parentParent;
}
}
Node* Find(const K& key) {
Node* cur = _root;
while (cur) {
if (key > kot(cur->_data)) cur = cur->_right;
else if (key < kot(cur->_data)) cur = cur->_left;
else return cur;
}
return nullptr;
}
void InOrder() {
_InOrder(_root);
cout << endl;
}
bool IsBalance() {
if (_root == nullptr) return true;
if (_root->_col == RED) return false;
int blacknum = 0;//根节点到当前节点的黑色节点数量
//blacknum只能传值,不能传引用。引用求得是整棵树所有黑色节点
//将最左路径节点作为参考值传入Check和其他路径比较
int refVal = 0;
Node* cur = _root;
while (cur) {
if (cur->_col == BLACK) ++refVal;
cur = cur->_left;
}
return Check(_root, blacknum, refVal);
}
int Height() { return _Height(_root); }
size_t Size() { return _Size(_root); }
private:
Node* _root = nullptr;
void _InOrder(Node* root) {
if (root == nullptr)
return;
_InOrder(root->_left);
cout << kot(root->_data) << " ";
_InOrder(root->_right);
}
bool Check(Node* root, int blacknum, const int refVal) {
if (root == nullptr) {
//cout << blacknum << endl;
//走到空意味着求出了一条路径的黑色节点数量
if (refVal != blacknum) {
cout << "存在黑色节点数量不相等的路径" << endl;
return false;
}
return true;
}
if (root->_col == RED && root->_parent->_col == RED) {
cout << "有连续的红色节点" << endl;
return false;
}
if (root->_col == BLACK) ++blacknum;
return Check(root->_left, blacknum, refVal)
&& Check(root->_right, blacknum, refVal);
}
int _Height(Node* root) {
if (root == nullptr) return 0;
int leftHeight = _Height(root->_left);
int rightHeight = _Height(root->_right);
return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
}
size_t _Size(Node* root) {
if (root == nullptr) return 0;
return _Size(root->_left) + _Size(root->_right) + 1;
}
};
4.3.2 set的模拟实现
MySet.h
#pragma once
#include "RBTree.h"
namespace bit {
template <class K>
class set {
public:
struct SetKeyOfT {
const K& operator() (const K& key) { return key; }
};
//红黑树的迭代器提供的是最基础的遍历功能,它只是简单地封装了节点指针,
//并提供 operator++、operator--、operator* 等基本操作。
//set 和 map 需要更严格的迭代器控制
//由于set和map的键(key)是排序的依据,必须保证键的不可变性,否则会破坏红黑树的有序性。因此:
//set的iterator和const_iterator都必须是const 迭代器(即 RBTree::const_iterator)。
//map 的 iterator 允许修改 value(pair.second),但禁止修改 key(pair.first)。
//map 的 const_iterator 完全禁止修改(key 和 value 都不能改)。
//typedef RBTree<K, K, SetKeyOfT>::iterator iterator;
//在模板编程中,当一个类型(如 iterator)依赖于模板参数(如 K)时,它被称为 “嵌套依赖类型”。
//这里,RBTree<K, K, SetKeyOfT>::iterator 的类型取决于模板参数 K,因此它是一个 嵌套依赖类型。
//C++ 编译器在解析模板时有一个特殊规则:
//默认情况下,编译器假定嵌套依赖名称(如 X::Y)是一个静态成员变量,而不是类型。
//如果 iterator 确实是类型,但未用 typename 声明,编译器会尝试将其解释为变量,导致错误。
//解决方案:必须用 typename 显式告诉编译器:“RBTree<K, ...>::iterator 是一个类型,而不是变量”。
typedef typename RBTree<K, K, SetKeyOfT>::const_iterator iterator;
typedef typename RBTree<K, K, SetKeyOfT>::const_iterator const_iterator;
//set只有key且不能修改,所以iterator和const_iterator都使用const_iterator
iterator begin() const { return _t.begin(); }
iterator end() const { return _t.end(); }
pair<iterator, bool> Insert(const K& key) { return _t.Insert(key); }
//仅仅将两个迭代器都改为const_iterator还是会报错
//set的Insert返回类型:其中 iterator 是 RBTree<K, K, SetKeyOfT>::const_iterator,
//即 __TreeIterator<T, const T&, const T*>。
//RBTree的Insert返回类型:其中iterator 是 __TreeIterator<T, T&, T*>(非 const 版本)。
private:
RBTree<K, K, SetKeyOfT> _t;
//set不能使用RBTree<const K, const K, SetKeyOfT> _t;
//虽然set的key不能修改,但是可能需要调整节点(如红黑树的旋转、变色)
//这些操作可能需要临时修改节点的 data(例如之前二叉搜索树的删除,需要交换节点)
//const K 会阻止这些操作,导致 RBTree 无法完成插入/删除的调整逻辑。
};
}
//红黑树的模版参数template <class K, class T, class KeyOfT>
//K的作用:K是键(Key)的类型,用于:比较节点:红黑树需要比较节点的键来决定插入、查找的位置。
//KeyOfT 仿函数从 T 中提取键(K)。
//set的T就是key,但map的T是pair<const K, V>。
//如果红黑树没有第一个参数K,那么set和map的比较、查找的逻辑就不一样。
//set可以直接使用T,但map需要先从T中获取key。这样红黑树的类模板就没办法做到统一。
4.3.3 map的模拟实现
MyMap.h
#pragma once
#include "RBTree.h"
namespace bit {
template <class K, class V>
class map {
public:
struct MapKeyOfT {
const K& operator() (const pair<K, V>& kv) { return kv.first; }
};
typedef typename RBTree<K, pair<const K, V>, MapKeyOfT>::iterator iterator;
typedef typename RBTree<K, pair<const 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); }
//first 和 second 都不可修改
//pair 对象本身不能被重新赋值。整个对象是只读的
//但它的 first 和 second 仍然可读(并用于构造新的 pair<const K, V>)。
//插入时,RBTree 会用 kv.first 和 kv.second 构造一个新的 pair<const K, V>
V& operator[](const K& key) {
//insert 返回值规范
//first: 指向已插入或已存在元素的迭代器
//second: 是否插入成功(true=新插入,false=已存在)
pair<iterator, bool> ret = Insert(make_pair(key, V()));
return ret.first->second;
//ret.first 是 iterator
//RBTree的模版参数template <class K, class T, class KeyOfT>
//map传给 RBTree 的模板参数是:RBTree<K, pair<const K, V>, MapKeyOfT>
//T = pair<const K, V>
//RBTreeNode中 T _data,所以 _data = pair<const K, V>
//迭代器中返回&_node->_data即(pair<const K, V>* )
}
private:
RBTree<K, pair<const K, V>, MapKeyOfT> _t;
};
}
作业
1. 下列说法正确的是()
A.set中的某个元素值不能被直接修改
B.map和unordered_map都是C++11提供的关联式容器
C.因为map和set的底层数据结构相同,因此在实现时set底层实际存储的是<key, key>的键值对
D.map和multimap中都重载了[]运算符
答案:A
A:正确,因为set要保证其有序,因此set中元素不能被直接修改,若要修改可以先删除,在插入
B:错误,map是C++98中已存在的,unordered_map是C++11中才有的
C:错误,map和set底层结构都是红黑树,而其底层红黑树在实现时并没有区分是存k模型还是KV 模型
D:错误,map中key是唯一的,每个key都有与之对应的value,经常需要通过key获取value,因此 map为了形象简 单重载了[]运算符, multimap中key是可以重复的,如果重载了[]运算符,给定 一个key时,就没有办法返回 value了,因此,multimap中没有重载[]运算符
2. 下面关于set的说法正确的是()
A.set中一定不能存储键值对,只能存储key
B.set可以将序列中重复性的元素去除掉
C.set中不能存储对象,因为对象字段较多,没有办法比较
D.set默认是升序,因为其默认是按照大于的方式比较的
答案:B
A:错误,set中可以存储键值对,实例化set时,将set中元素类型设置为pair即可
B:正确,因为set中的key是不能重复的
C:错误,set中任意类型元素都可以存储,存储对象时,需要用户提供比较规则
D:错误,set默认是升序,正确,但是其内部默认不是按照大于比较,而是按照小于比较
3. 下面关于map的说法正确的是()
A.map的查询效率是O(log_2N),因为其底层使用的是二叉搜索树
B.map的key和value的类型可以相同
C.map中的有序只能是升序,不能是降序
D.map中的key可以直接修改
答案:B
A:错误,map的查询效率是O(log_2N)是正确的,但map的底层结构不是二叉搜索树,而是红黑树
B:正确,key和value的类型由用户自己设置,可以相同也可以不同,取决于应用场景需要
C:错误,map可以是升序,也可是降序,默认情况下是升序,如果需要降序,需要用户在实例化map时指定比较规则
D:错误,map中key不能修改,因为如果修改了就不能保证红黑树的特性了,即有序
4. 下面关于map和set说法错误的是()
A.map中存储的是键值对,set中只储存了key
B.map和set查询的时间复杂度都是O(log_2N)
C.map和set都重载了[]运算符
D.map和set底层都是使用红黑树实现的
答案:C
A:正确,map和set的概念
B:正确,因map和set的底层结构都是红黑树,而红黑树是近似的平衡二叉搜索树,故查询时间复杂度为O(log_2N)
C:错误,map中重载了[]运算符,因为其需要通过key获取value,set中没有
D:正确
5. 单词识别 单词识别_牛客题霸_牛客网
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
struct KvCom{
bool operator()(const pair<string, int>& kv1, const pair<string, int>& kv2) {
// return kv1.second > kv2.second;//不能只比较value
return kv1.second > kv2.second ||
(kv1.second == kv2.second && kv1.first < kv2.first);
}
};
int main() {
string input;
getline(cin, input); // 读取整行输入
map<string, int> wordCount; // 存储单词及其出现次数
string currentWord;
for (char ch : input) {
if (isalpha(ch)) { // 如果是字母,加入当前单词
currentWord += tolower(ch); // 转换为小写
} else if (ch == '.') { // 如果是句号,跳过
continue;
} else { // 不是字母,不是句号,就只会是空格
if (!currentWord.empty()) { //读取单词的string不为空就插入map
wordCount[currentWord]++;
currentWord.clear();//清除currentWord里的单词准备读取下一个
}
}
}
// 处理最后一个单词(如果输入不以空格或句号结尾)
if (!currentWord.empty()) {
wordCount[currentWord]++;
}
// 将 map 转换为 vector 以便排序
vector<pair<string, int>> words(wordCount.begin(), wordCount.end());
sort(words.begin(), words.end(), KvCom());
// 输出结果
for (auto& kv : words) {
cout << kv.first << ":" << kv.second << endl;
}
return 0;
}
6. 关于AVL树的旋转说法正确的是()
A.插入时,AVL树最多只需要旋转两次
B.删除时,只要某个节点的平衡因子不满足特性时 ,只需要对该棵子树进行旋转,就可以使AVL树再次平衡
C.AVL树的节点中必须维护平衡因子,因为要依靠其平衡因子是否需要旋转以维护其平衡性
D.AVL树的双旋转只需要直接使用对应的单旋转即可
答案:A
A:正确,即双旋
B:错误,可能需要旋转多次,子树旋转后,其高度降低了一层,其上层可能也需要跟着旋转
C:错误,平衡因子不是必须要维护的,在操作时也可以直接通过高度函数来算,只不过比较麻烦
D:错误,不能直接使用单旋转,因为两个单旋转完成后,还需要对部分节点的平衡因子进行更新
7. 现有一棵无重复关键字的平衡二叉树(AVL树),对其进行中序遍历可得到一个降序序列。下列关于该平衡二叉树的叙述中,正确的是()
A.根结点的度一定为2
B.树中最小元素一定是叶结点
C.最后插入的元素一定是叶结点
D.树中最大元素一定是无左子树
答案:D
题目中说:中序遍历得到一个降序序列,则说明:根小于左子树中节点,大于右子树中节点
A:错误,根可以没有左子树,比如树中只有两个节点,即根以及根的右子树
B:错误,树中最小的元素一定是最左侧或者最右侧节点,但不一定是叶子节点
C:错误,最后插入的元素不一定是叶子节点,因为新节点插入后,为了保证其平衡性,还要对树进行旋转处理,旋转之后,就不一定在叶子的位置
D:正确,因为最大元素如果存在左子树,中序遍历就不可能是降序序列
8. 下面关于AVL树说法不正确的是()
A.AVL树也是二叉搜索树
B.极端情况下,AVL树可能也会退化成单支树
C.AVL查询的时间复杂度是O(log_2N)
D.AVL树是通过平衡因子限制保证其平衡性的
答案:B
AVL树:一棵AVL树或者是空树,或者是具有以下性质的二叉搜索树
1. 它的左右子树都是AVL树
2. 左右子树高度之差(简称平衡因子)的绝对值不超过1(-1 / 0 / 1)
故:如果一棵二叉搜索树是高度平衡的,它就是AVL树。如果它有n个结点,其高度可保持在O(logN),搜索时间复杂度O(logN)
A:正确,参考上述概念
B:错误,AVL树没有极端情况,其是为了防止二叉搜索树的极端情况二给出的
C:正确,参考上述概念
D:正确,平衡因子:左右子树高度之间,其绝对值如果不超过1,则认为树就是平衡的
9. 关于AVL树和红黑树的区别说法不正确的是()
A.AVL树和红黑树保证平衡性的方式不同
B.AVL树和红黑树都是平衡树,因此查找的时间复杂度都是O(log_2N)
C.AVL树和红黑树的性质遭到破坏时,都需要进行旋转
D.AVL树和红黑树中序遍历都可以得到有序序列,因为它们都是二叉搜索树
答案:C
A:正确,AVL树通过节点的平衡因子保证,红黑树通过节点的颜色以及红黑树的特性保证
B:正确,AVL树是严格平衡的,红黑树虽然是近似平衡,但其性能往往比AVL树好,而且实现简单,因此他们的查找效率都是O(logN)
C:错误,AVL树是一定需要旋转,红黑树不一定,红黑树有时只需要改变节点的颜色即可
D:正确,参考概念
10. 下面关于红黑树的特性说法错误的是()
A.红黑树最左侧节点一定是最小的,最右侧节点一定是最大的
B.红黑树在实现时必须要有头结点
C.红黑树中可能会出现连在一起的黑色节点
D.红黑树的旋转不需要依靠平衡因子
答案:B
A:该题不严谨,这个取决于红黑树中元素的比较规则,最左侧节点可能是最大的,也可能是最小的,没有规定,取决于创建树时的比较方式
B:错误,红黑树在实现时可以没有头节点,这个根据需要是否给出
C:正确,但是一定不能出现连在一起的红色节点
D:正确,红黑树是通过节点颜色以及红黑树的性质来保证其平衡性的,AVL树需要平衡因子保证
11. 红黑树的插入算法复杂度最坏情况是 ()
A.O(n)
B.O(log(n))
C.O(nlog(n))
D.其他都不对
答案:B
红黑树是近似的平衡树,没有什么最坏情况,插入的时间复杂度为O(log(N))
12. 关于红黑树以下说法正确的是()
A.空树不是红黑树,因为红黑树要求根节点必须为黑色,而空树中没有根节点
B.红黑树也是二叉搜索树,因此其按照前序遍历可以得到有序序列
C.红黑树是一棵真正平衡的二叉树
D.红黑树最长路径中节点个数可能会等于最短路径中节点个数的两倍
答案:D
A:错误,空树也是红黑树,性质5中规定树中的空指针域为叶子节点,因此空树也是有节点的
B:错误,红黑树也是二叉搜索树,按照中序遍历才可以得到有序序列
C:红黑树不像AVL树那么严格,是一棵近似平衡的二叉搜索树
D:正确,比如红黑树中只有两个节点
377

被折叠的 条评论
为什么被折叠?



