• <二叉搜索树>——《C++高阶》


    目录

    1.内容说明: 

    2. 二叉搜索树

    2.1 二叉搜索树概念

    2.2 二叉搜索树操作

    1. 二叉搜索树的查找

    2. 二叉搜索树的插入

    3. 二叉搜索树的删除

    2.3 二叉搜索树的实现

    2.4 二叉搜索树的应用

    2.5 二叉搜索树的性能分析

    3.二叉搜索树的模拟实现:

    3.1二叉搜索树(K模型)

    3.1.1定义二叉搜索树的结构:​

    3.1.2功能函数:

    (1)非递归版Insert:​

    (2)非递归版Find​

    (3)非递归版Erase​

    (4)递归版InsertR:

    ​(5)递归版FindR​

    (6)递归版EraseR:​

    3.1.3: 遍历(递归版):

    3.1.4完整源码:

    (1)BSTreeKey.h:

    (2)test.cpp:

    3.2二叉搜索树(KV模型) 

    3.2.1 二叉树KV模型结构定义:​

    3.2.2功能函数

    (1)非递归版Insert、Find、Erase​

    (2)递归版InsertR、FindR、EraseR:​

     3.2.3遍历(递归版):

     3.2.4完整源码:

    (1)BSTreeKeyValue.h:

    (2)test.cpp:

    后记:●由于作者水平有限,文章难免存在谬误之处,敬请读者斧正,俚语成篇,恳望指教!

                                                                           ——By 作者:新晓·故知


    1.内容说明: 

    二叉树在前面C数据结构阶段已经学习了解,这里开始新的章节学习:
    1. map和set特性需要先铺垫二叉搜索树,而二叉搜索树也是一种树形结构
    2. 二叉搜索树的特性了解,有助于更好的理解map和set的特性
    3. 二叉树中部分面试题稍微有点难度,在前面学习不容易接受,且时间长容易忘
    4. 有些OJ题使用C语言方式实现比较麻烦
    因此这里学习二叉树搜索树,对二叉树部分进行总结。

    2. 二叉搜索树

    2.1 二叉搜索树概念

    二叉搜索树又称二叉排序树,它或者是一棵空树,或者是具有以下性质的二叉树:
    若它的左子树不为空,则左子树上所有节点的值都小于根节点的值
    若它的右子树不为空,则右子树上所有节点的值都大于根节点的值
    它的左右子树也分别为二叉搜索树

     int a [] = {5,3,4,1,7,8,2,6,0,9};

    2.2 二叉搜索树操作

    1. 二叉搜索树的查找

    2. 二叉搜索树的插入

    插入的具体过程如下:
    a. 树为空,则直接插入

     

     b. 树不空,按二叉搜索树性质查找插入位置,插入新节点

    3. 二叉搜索树的删除

    首先查找元素是否在二叉搜索树中,如果不存在,则返回, 否则要删除的结点可能分下面四种情况:
    a. 要删除的结点无孩子结点
    b. 要删除的结点只有左孩子结点
    c. 要删除的结点只有右孩子结点
    d. 要删除的结点有左、右孩子结点
    看起来有待删除节点有4中情况,实际情况a可以与情况b或者c合并起来,因此真正的删除过程如下:
    情况b:删除该结点且使被删除节点的双亲结点指向被删除节点的左孩子结点
    情况c:删除该结点且使被删除节点的双亲结点指向被删除结点的右孩子结点
    情况d:在它的右子树中寻找中序下的第一个结点(关键码最小),用它的值填补到被删除节点中, 再来处理该结点的删除问题

     2.3 二叉搜索树的实现

    1. template<class T>
    2. struct BSTNode
    3. {
    4. BSTNode(const T& data = T())
    5. : _pLeft(nullptr), _pRight(nullptr), _data(data)
    6. {}
    7. BSTNode* _pLeft;
    8. BSTNode* _pRight;
    9. T _data;
    10. };
    11. template<class T>
    12. class BSTree
    13. {
    14. typedef BSTNode Node;
    15. typedef Node* PNode;
    16. public:
    17. BSTree() : _pRoot(nullptr)
    18. {}
    19. // 同学们自己实现,与二叉树的销毁类似
    20. ~BSTree();
    21. // 根据二叉搜索树的性质查找:找到值为data的节点在二叉搜索树中的位置
    22. PNode Find(const T& data);
    23. bool Insert(const T& data)
    24. {
    25. // 如果树为空,直接插入
    26. if (nullptr == _pRoot)
    27. {
    28. _pRoot = new Node(data);
    29. return true;
    30. }
    31. // 按照二叉搜索树的性质查找data在树中的插入位置
    32. PNode pCur = _pRoot;
    33. // 记录pCur的双亲,因为新元素最终插入在pCur双亲左右孩子的位置
    34. PNode pParent = nullptr;
    35. while (pCur)
    36. {
    37. pParent = pCur;
    38. if (data < pCur->_data)
    39. pCur = pCur->_pLeft;
    40. else if (data > pCur->_data)
    41. pCur = pCur->_pRight; // 元素已经在树中存在
    42. else
    43. return false;
    44. }
    45. // 插入元素
    46. pCur = new Node(data);
    47. if (data < pParent->_data)
    48. pParent->_pLeft = pCur;
    49. else
    50. pParent->_pRight = pCur; return true;
    51. }
    52. bool Erase(const T& data)
    53. {
    54. // 如果树为空,删除失败
    55. if (nullptr == _pRoot)
    56. return false;
    57. // 查找在data在树中的位置
    58. PNode pCur = _pRoot;
    59. PNode pParent = nullptr;
    60. while (pCur)
    61. {
    62. if (data == pCur->_data)
    63. break;
    64. else if (data < pCur->_data)
    65. {
    66. pParent = pCur;
    67. pCur = pCur->_pLeft;
    68. }
    69. else
    70. {
    71. pParent = pCur;
    72. pCur = pCur->_pRight;
    73. }
    74. }
    75. // data不在二叉搜索树中,无法删除
    76. if (nullptr == pCur)
    77. return false;
    78. // 分以下情况进行删除,同学们自己画图分析完成
    79. if (nullptr == pCur->_pRight)
    80. {
    81. // 当前节点只有左孩子或者左孩子为空---可直接删除
    82. }
    83. else if (nullptr == pCur->_pRight)
    84. {
    85. // 当前节点只有右孩子---可直接删除
    86. }
    87. else
    88. {
    89. // 当前节点左右孩子都存在,直接删除不好删除,可以在其子树中找一个替代结点,比如:
    90. // 找其左子树中的最大节点,即左子树中最右侧的节点,或者在其右子树中最小的节点,即右子树中最小的节点
    91. // 替代节点找到后,将替代节点中的值交给待删除节点,转换成删除替代节点
    92. }
    93. return true;
    94. }
    95. // 同学们自己实现
    96. void InOrder();
    97. private:
    98. PNode _pRoot;
    99. }

    2.4 二叉搜索树的应用

    1. K模型:K模型即只有key作为关键码,结构中只需要存储Key即可,关键码即为需要搜索到的值
    比如:给一个单词word,判断该单词是否拼写正确,具体方式如下:
    以单词集合中的每个单词作为key,构建一棵二叉搜索树
    在二叉搜索树中检索该单词是否存在,存在则拼写正确,不存在则拼写错误。
    2. KV模型:每一个关键码key,都有与之对应的值Value,即的键值对。该种方式在现实生活中非常常见:比如英汉词典就是英文与中文的对应关系,通过英文可以快速找到与其对应的中文,英文单词与其对应的中文就构成一种键值对;再比如统计单词次数,统计成功后,给定单词就可快速找到其出现的次数,单词与其出现次数就是就构成一种键值对
    比如:实现一个简单的英汉词典dict,可以通过英文找到与其对应的中文,具体实现方式如下: <单词,中文含义>为键值对构造二叉搜索树,注意:二叉搜索树需要比较,键值对比较时只比较 Key 查询英文单词时,只需给出英文单词,就可快速找到与其对应的key

    1. template<class K, class V>
    2. struct BSTNode
    3. {
    4. BSTNode(const K& key = K(), const V& value = V())
    5. : _pLeft(nullptr), _pRight(nullptr), _key(key), _Value(value)
    6. {}
    7. BSTNode* _pLeft;
    8. BSTNode* _pRight;
    9. K _key;
    10. V _value
    11. };
    12. template<class K, class V>
    13. class BSTree
    14. {
    15. typedef BSTNode Node;
    16. typedef Node* PNode;
    17. public:
    18. BSTree() : _pRoot(nullptr)
    19. {}
    20. // 同学们自己实现,与二叉树的销毁类似
    21. ~BSTree();
    22. // 根据二叉搜索树的性质查找:找到值为data的节点在二叉搜索树中的位置
    23. PNode Find(const K& key);
    24. bool Insert(const K& key, const V& value)
    25. {
    26. // ...
    27. PNode pCur = _pRoot;
    28. PNode pParent = nullptr;
    29. while (pCur)
    30. {
    31. pParent = pCur;
    32. if (key < pCur->_key)
    33. pCur = pCur->_pLeft;
    34. else if (key > pCur->_key)
    35. pCur = pCur->_pRight; // 元素已经在树中存在
    36. else
    37. return false;
    38. }
    39. // ...
    40. return true;
    41. }
    42. bool Erase(const K& key)
    43. {
    44. // ...
    45. return true;
    46. }
    47. private:
    48. PNode _pRoot;
    49. };

    插入数据,然后去重,进行排序

    递归的问题:虽然代码简短,但如果深度太大,可能会溢出。

    2.5 二叉搜索树的性能分析

    插入和删除操作都必须先查找,查找效率代表了二叉搜索树中各个操作的性能。
    对有n个结点的二叉搜索树,若每个元素查找的概率相等,则二叉搜索树平均查找长度是结点在二叉搜索树的深度的函数,即结点越深,则比较次数越多。
    但对于同一个关键码集合,如果各关键码插入的次序不同,可能得到不同结构的二叉搜索树:
    问题:如果退化成单支树,二叉搜索树的性能就失去了。那能否进行改进,不论按照什么次序插入关键码,都可以是二叉搜索树的性能最佳?

    3.二叉搜索树的模拟实现:

    3.1二叉搜索树(K模型)

     3.1.1定义二叉搜索树的结构:

     

    3.1.2功能函数:

    (1)非递归版Insert:

     (2)非递归版Find

     (3)非递归版Erase

    (4)递归版InsertR:

     (5)递归版FindR

    (6)递归版EraseR: 3.1.3: 遍历(递归版):

    中序遍历、前序遍历、后序遍历

     

    3.1.4 完整源码:

    (1)BSTreeKey.h:

    1. #pragma once
    2. //二叉搜索树 BinarySearchTree K模型
    3. //一般不允许冗余,会进行去重,所以可有使用搜索树去重
    4. #include
    5. using namespace std;
    6. template<class K> //根据传过来的值类型,K即为类型。例int、double等
    7. struct BSTreeNode
    8. {
    9. BSTreeNode* _left;
    10. BSTreeNode* _right;
    11. K _key; //类型为K的类型,一般不允许修改,防止破坏树形结构
    12. BSTreeNode(const K& key)
    13. :_left(nullptr)
    14. , _right(nullptr)
    15. , _key(key)
    16. {}
    17. };
    18. template<class K>
    19. class BSTree
    20. {
    21. typedef BSTreeNode Node;
    22. public:
    23. //C++11支持default
    24. BSTree() = default; //拷贝构造函数也是构造函数,只要写构造函数就不会生成默认构造,这里强制生成构造函数
    25. Node* CopyTree(Node* root)
    26. {
    27. if (root == nullptr)
    28. return nullptr;
    29. Node* copyNode = new Node(root->_key);
    30. copyNode->_left = CopyTree(root->_left);
    31. copyNode->_right = CopyTree(root->_right);
    32. return copyNode;
    33. }
    34. BSTree(const BSTree& t) //实现深拷贝
    35. {
    36. _root = CopyTree(t._root);
    37. }
    38. //赋值重载 例:t2=t1;
    39. //现代写法
    40. BSTree& operator=(BSTree t)
    41. {
    42. swap(_root, t._root);
    43. return *this;
    44. }
    45. void DestroyTree(Node* root)
    46. {
    47. if (root == nullptr)
    48. return;
    49. DestroyTree(root->_left);
    50. DestroyTree(root->_right);
    51. delete root;
    52. }
    53. ~BSTree() //因为析构函数没有参数,要写成递归就得借用成员函数,嵌套一层
    54. {
    55. DestroyTree(_root);
    56. _root = nullptr;
    57. }
    58. //非递归insert
    59. bool Insert(const K& key) //一般不允许冗余,会进行去重
    60. {
    61. if (_root == nullptr)
    62. {
    63. _root = new Node(key);
    64. return true;
    65. }
    66. Node* parent = nullptr;
    67. Node* cur = _root;
    68. while (cur)
    69. {
    70. //不允许冗余
    71. if (cur->_key < key)
    72. {
    73. parent = cur;
    74. cur = cur->_right;
    75. }
    76. else if (cur->_key > key)
    77. {
    78. parent = cur;
    79. cur = cur->_left;
    80. }
    81. else
    82. {
    83. return false;
    84. }
    85. /*//允许冗余
    86. if (cur->_key < key)
    87. {
    88. parent = cur;
    89. cur = cur->_right;
    90. }
    91. else
    92. {
    93. parent = cur;
    94. cur = cur->_left;
    95. }*/
    96. }
    97. cur = new Node(key);
    98. if (parent->_key < key)
    99. {
    100. parent->_right = cur;
    101. }
    102. else
    103. {
    104. parent->_left = cur;
    105. }
    106. return true;
    107. }
    108. //非递归find
    109. bool Find(const K& key)
    110. {
    111. Node* cur = _root;
    112. while (cur)
    113. {
    114. if (cur->_key < key)
    115. {
    116. cur = cur->_right;
    117. }
    118. else if (cur->_key > key)
    119. {
    120. cur = cur->_left;
    121. }
    122. else
    123. {
    124. return true;
    125. }
    126. }
    127. return false;
    128. }
    129. //非递归erase
    130. //删除情况很多,需要分情况讨论
    131. //1.当删除的是父结点时,采用替换法:
    132. //找父结点的左子树的(所有值的)最大值结点或右子树的(所有值的)最小值结点替换被删除的父结点
    133. //2.当删除的是叶结点,直接删除,再链接
    134. bool Erase(const K& key)
    135. {
    136. Node* parent = nullptr;
    137. Node* cur = _root;
    138. while (cur)
    139. {
    140. if (cur->_key < key)
    141. {
    142. parent = cur;
    143. cur = cur->_right;
    144. }
    145. else if (cur->_key > key)
    146. {
    147. parent = cur;
    148. cur = cur->_left;
    149. }
    150. else
    151. {
    152. //一个孩子--左为空or右为空
    153. if (cur->_left == nullptr)
    154. {
    155. //if(parent==nullptr)
    156. if (cur == _root)
    157. {
    158. _root = cur->_right;
    159. }
    160. else
    161. {
    162. if (cur == parent->_left)
    163. {
    164. parent->_left = cur->_right;
    165. }
    166. else
    167. {
    168. parent->_right = cur->_right;
    169. }
    170. }
    171. delete cur;
    172. }
    173. else if (cur->_right == nullptr)
    174. {
    175. //if(parent==nullptr)
    176. if (cur == _root)
    177. {
    178. _root = cur->_left;
    179. }
    180. else
    181. {
    182. if (cur == parent->_left)
    183. {
    184. parent->_left = cur->_left;
    185. }
    186. else
    187. {
    188. parent->_right = cur->_left;
    189. }
    190. }
    191. delete cur;
    192. }
    193. else //两个孩子都不为空 //删除有两个孩子的结点:替换法
    194. {
    195. //1.使用右子树的最小值结点替代
    196. Node* minParent = cur;
    197. Node* minRight = cur->_right;
    198. while (minRight->_left)
    199. {
    200. minParent = minRight;
    201. minRight = minRight->_left;
    202. }
    203. swap(minRight->_key, cur->_key); //或cur->_key = minRight->_key;
    204. if (minParent->_left == minRight)
    205. {
    206. minParent->_left = minRight->_right;
    207. }
    208. else
    209. {
    210. minParent->_right = minRight->_right;
    211. }
    212. delete minRight;
    213. 2.使用左子树的最大值结点替代
    214. //Node* maxParent = cur;
    215. //Node* maxLeft = cur->_left;
    216. //while (maxLeft->_right)
    217. //{
    218. // maxParent = maxLeft;
    219. // maxLeft = maxLeft->_right;
    220. //}
    221. //swap(maxLeft->_key, cur->_key); //或cur->_key = maxLeft->_key;
    222. //if (maxParent->_right == maxLeft)
    223. //{
    224. // maxParent->_right = maxLeft->_left;
    225. //}
    226. //else
    227. //{
    228. // maxParent->_left = maxLeft->_left;
    229. //}
    230. //delete maxLeft;
    231. }
    232. return true;
    233. }
    234. }
    235. return false;
    236. }
    237. /
    238. //递归
    239. //无法直接使用私有成员进行递归,因此嵌套一层成员函数,实现递归
    240. //递归find
    241. bool FindR(const K& key)
    242. {
    243. return _FindR(_root, key);
    244. }
    245. //递归insert
    246. bool InsertR(const K& key)
    247. {
    248. return _InsertR(_root, key);
    249. }
    250. //递归erase
    251. bool EraseR(const K& key)
    252. {
    253. return _EraseR(_root, key);
    254. }
    255. private:
    256. //递归insert
    257. bool _InsertR(Node*& root, const K& key)
    258. {
    259. //Node*& root这个处理,使得当root为空指针时,但root同时也是父结点的left或right的别名,使得结点得以链接
    260. if (root == nullptr)
    261. {
    262. root = new Node(key);
    263. return true;
    264. }
    265. if (root->_key < key)
    266. return _InsertR(root->_right, key);
    267. else if (root->_key > key)
    268. return _InsertR(root->_left, key);
    269. else
    270. return false;
    271. }
    272. //递归FindR
    273. bool _FindR(Node* root, const K& key)
    274. {
    275. if (root == nullptr)
    276. return false;
    277. if (root->_key < key)
    278. {
    279. return _FindR(root->_right, key);
    280. }
    281. else if (root->_key > key)
    282. {
    283. return _FindR(root->_left, key);
    284. }
    285. else
    286. {
    287. return true;
    288. }
    289. }
    290. //递归erase
    291. bool _EraseR(Node*& root, const K& key)
    292. {
    293. if (root == nullptr)
    294. return false;
    295. if (root->_key < key)
    296. {
    297. return _EraseR(root->_right, key);
    298. }
    299. else if (root->_key > key)
    300. {
    301. return _EraseR(root->_left, key);
    302. }
    303. else
    304. {
    305. Node* del = root; //先保存一下
    306. if (root->_left == nullptr)
    307. {
    308. root = root->_right;
    309. }
    310. else if (root->_right == nullptr)
    311. {
    312. root = root->_left;
    313. }
    314. else
    315. {
    316. //1.使用右子树的最小值结点替代
    317. Node* minRight = root->_right;
    318. while (minRight->_left)
    319. {
    320. minRight = minRight->_left;
    321. }
    322. swap(root->_key, minRight->_key);
    323. return _EraseR(root->_right, key);
    324. 2.使用左子树的最大值结点替代
    325. //Node* maxLeft = root->_left;
    326. //while (maxLeft->_right)
    327. //{
    328. // maxLeft = maxLeft->_right;
    329. //}
    330. //swap(root->_key, maxLeft->_key);
    331. //return _EraseR(root->_left, key);
    332. }
    333. delete del;
    334. return true;
    335. }
    336. }
    337. public:
    338. //递归版遍历
    339. void InOrder() //1.中序遍历
    340. {
    341. _InOrder(_root);
    342. cout << endl;
    343. }
    344. void PrevOrder() //2.前序遍历
    345. {
    346. _PrevOrder(_root);
    347. cout << endl;
    348. }
    349. void PostOrder() //3.后序遍历
    350. {
    351. _PostOrder(_root);
    352. cout << endl;
    353. }
    354. private:
    355. //在C语言中,root可以被直接获取,
    356. //在C++中,因为_root 是私有,被封装起来了所以可有以下两种方式获得
    357. //1.可以写一个成员函数GetRoot()获取
    358. //2.也可以使用遍历,不被继承就设为私有成员函数
    359. void _InOrder(Node* root) //1.中序遍历
    360. {
    361. if (root == nullptr)
    362. return;
    363. _InOrder(root->_left);
    364. cout << root->_key << " ";
    365. _InOrder(root->_right);
    366. }
    367. void _PrevOrder(Node* root) //2.前序遍历
    368. {
    369. if (root == nullptr)
    370. return;
    371. cout << root->_key << " ";
    372. _PrevOrder(root->_left);
    373. _PrevOrder(root->_right);
    374. }
    375. void _PostOrder(Node* root) //3.后序遍历
    376. {
    377. if (root == nullptr)
    378. return;
    379. _PostOrder(root->_left);
    380. _PostOrder(root->_right);
    381. cout << root->_key << " ";
    382. }
    383. private:
    384. Node* _root = nullptr; //调用自定义类型Node*
    385. };

    (2)test.cpp:

    1. #include"BSTreeKey.h"
    2. void TestBSTree1()
    3. {
    4. BSTree<int> t;
    5. //int a[] = {8,3,1,10,6,4,7,14,13 };
    6. //int a[] = {8,3,1,10,6,4,7,14,13,10,6 }; //冗余测试
    7. int a[] = { 5,3,4,1,7,8,2,6,0,9 };
    8. for (auto e : a)
    9. {
    10. t.Insert(e);
    11. }
    12. t.InOrder();
    13. t.Insert(16);
    14. t.Insert(9);
    15. t.InOrder();
    16. }
    17. void TestBSTree2()
    18. {
    19. BSTree<int> t;
    20. int a[] = { 8,3,1,10,6,4,7,14,13 };
    21. //int a[] = {8,3,1,10,6,4,7,14,13,10,6 }; //冗余测试
    22. //int a[] = { 5,3,4,1,7,8,2,6,0,9 };
    23. for (auto e : a)
    24. {
    25. t.Insert(e);
    26. }
    27. t.InOrder();
    28. t.PrevOrder();
    29. t.PostOrder();
    30. //t.Erase(8);
    31. //t.Erase(10);
    32. //t.Erase(3);
    33. //t.Erase(7);
    34. //t.Erase(6);
    35. //t.Erase(14);
    36. //t.Erase(13);
    37. //t.InOrder();
    38. /*for (auto e : a)
    39. {
    40. t.Erase(e);
    41. }
    42. t.InOrder();*/
    43. }
    44. void TestBSTree3()
    45. {
    46. BSTree<int> t;
    47. int a[] = { 8,3,1,10,6,4,7,14,13 };
    48. //int a[] = {8,3,1,10,6,4,7,14,13,10,6 }; //冗余测试
    49. //int a[] = { 5,3,4,1,7,8,2,6,0,9 };
    50. //非递归insert
    51. /*for (auto e : a)
    52. {
    53. t.Insert(e);
    54. }*/
    55. //递归insertR
    56. /*for (auto e : a)
    57. {
    58. t.InsertR(e);
    59. }
    60. t.InOrder();*/
    61. //BSTree copy=t; //浅拷贝
    62. //copy.InOrder();
    63. t.Find(10);
    64. t.FindR(10);
    65. }
    66. void TestBSTree4()
    67. {
    68. BSTree<int> t;
    69. int a[] = { 8,3,1,10,6,4,7,14,13 };
    70. //int a[] = {8,3,1,10,6,4,7,14,13,10,6 }; //冗余测试
    71. //int a[] = { 5,3,4,1,7,8,2,6,0,9 };
    72. //非递归insert
    73. for (auto e : a)
    74. {
    75. t.Insert(e);
    76. }
    77. //递归insertR
    78. /*for (auto e : a)
    79. {
    80. t.InsertR(e);
    81. }*/
    82. t.InOrder();
    83. t.EraseR(13);
    84. t.EraseR(10);
    85. t.EraseR(8);
    86. t.EraseR(3);
    87. t.InOrder();
    88. for (auto e : a)
    89. {
    90. t.EraseR(e);
    91. }
    92. t.InOrder();
    93. }
    94. int main()
    95. {
    96. //TestBSTree1();
    97. //TestBSTree2();
    98. //TestBSTree3();
    99. TestBSTree4();
    100. return 0;
    101. }

    可画功能函数递归展开图进行分析

    3.2二叉搜索树(KV模型) 

    3.2.1 二叉树KV模型结构定义:

     

    3.2.2功能函数

    (1)非递归版Insert、Find、Erase 

    (2)递归版InsertR、FindR、EraseR: 3.2.3遍历(递归版):

    中序遍历、前序遍历、后序遍历:

     

     3.2.4完整源码:

    (1)BSTreeKeyValue.h:

    1. #pragma once
    2. //二叉搜索树 BinarySearchTree-KeyValue模型
    3. #include
    4. #include
    5. using namespace std;
    6. template<class K,class V>
    7. struct BSTreeNode
    8. {
    9. BSTreeNode* _left;
    10. BSTreeNode* _right;
    11. K _key; //一般不允许修改key,防止树型结构变化
    12. V _value;
    13. BSTreeNode(const K& key,const V& value)
    14. :_left(nullptr)
    15. , _right(nullptr)
    16. , _key(key)
    17. ,_value(value)
    18. {}
    19. };
    20. template<class K, class V>
    21. class BSTree
    22. {
    23. typedef BSTreeNode Node;
    24. public:
    25. //C++11支持default
    26. BSTree() = default; //拷贝构造函数也是构造函数,只要写构造函数就不会生成默认构造,这里强制生成构造函数
    27. Node* CopyTree(Node* root)
    28. {
    29. if (root == nullptr)
    30. return nullptr;
    31. Node* copyNode = new Node(root->_key,root->_value);
    32. copyNode->_left = CopyTree(root->_left);
    33. copyNode->_right = CopyTree(root->_right);
    34. return copyNode;
    35. }
    36. BSTree(const BSTree& t) //实现深拷贝
    37. {
    38. _root = CopyTree(t._root);
    39. }
    40. //赋值重载 例:t2=t1;
    41. //现代写法
    42. BSTree& operator=(BSTree t)
    43. {
    44. swap(_root, t._root);
    45. return *this;
    46. }
    47. void DestroyTree(Node* root)
    48. {
    49. if (root == nullptr)
    50. return;
    51. DestroyTree(root->_left);
    52. DestroyTree(root->_right);
    53. delete root;
    54. }
    55. ~BSTree() //因为析构函数没有参数,要写成递归就得借用成员函数,嵌套一层
    56. {
    57. DestroyTree(_root);
    58. _root = nullptr;
    59. }
    60. //非递归insert
    61. bool Insert(const K& key,const V& value) //虽然传了key和value,但只用key比较
    62. {
    63. if (_root == nullptr)
    64. {
    65. _root = new Node(key,value);
    66. return true;
    67. }
    68. Node* parent = nullptr;
    69. Node* cur = _root;
    70. while (cur)
    71. {
    72. //不允许冗余
    73. if (cur->_key < key)
    74. {
    75. parent = cur;
    76. cur = cur->_right;
    77. }
    78. else if (cur->_key > key)
    79. {
    80. parent = cur;
    81. cur = cur->_left;
    82. }
    83. else
    84. {
    85. return false;
    86. }
    87. /*//允许冗余
    88. if (cur->_key < key)
    89. {
    90. parent = cur;
    91. cur = cur->_right;
    92. }
    93. else
    94. {
    95. parent = cur;
    96. cur = cur->_left;
    97. }*/
    98. }
    99. cur = new Node(key,value);
    100. if (parent->_key < key)
    101. {
    102. parent->_right = cur;
    103. }
    104. else
    105. {
    106. parent->_left = cur;
    107. }
    108. return true;
    109. }
    110. //非递归find
    111. Node* Find(const K& key)
    112. {
    113. Node* cur = _root;
    114. while (cur)
    115. {
    116. if (cur->_key < key)
    117. {
    118. cur = cur->_right;
    119. }
    120. else if (cur->_key > key)
    121. {
    122. cur = cur->_left;
    123. }
    124. else
    125. {
    126. return cur;
    127. }
    128. }
    129. return nullptr;
    130. }
    131. //非递归erase
    132. //删除情况很多,需要分情况讨论
    133. //1.当删除的是父结点时,采用替换法:
    134. //找父结点的左子树的(所有值的)最大值结点或右子树的(所有值的)最小值结点替换被删除的父结点
    135. //2.当删除的是叶结点,直接删除,再链接
    136. bool Erase(const K& key)
    137. {
    138. Node* parent = nullptr;
    139. Node* cur = _root;
    140. while (cur)
    141. {
    142. if (cur->_key < key)
    143. {
    144. parent = cur;
    145. cur = cur->_right;
    146. }
    147. else if (cur->_key > key)
    148. {
    149. parent = cur;
    150. cur = cur->_left;
    151. }
    152. else
    153. {
    154. //一个孩子--左为空or右为空
    155. if (cur->_left == nullptr)
    156. {
    157. //if(parent==nullptr)
    158. if (cur == _root)
    159. {
    160. _root = cur->_right;
    161. }
    162. else
    163. {
    164. if (cur == parent->_left)
    165. {
    166. parent->_left = cur->_right;
    167. }
    168. else
    169. {
    170. parent->_right = cur->_right;
    171. }
    172. }
    173. delete cur;
    174. }
    175. else if (cur->_right == nullptr)
    176. {
    177. //if(parent==nullptr)
    178. if (cur == _root)
    179. {
    180. _root = cur->_left;
    181. }
    182. else
    183. {
    184. if (cur == parent->_left)
    185. {
    186. parent->_left = cur->_left;
    187. }
    188. else
    189. {
    190. parent->_right = cur->_left;
    191. }
    192. }
    193. delete cur;
    194. }
    195. else //两个孩子都不为空 //删除有两个孩子的结点:替换法
    196. {
    197. //1.使用右子树的最小值结点替代
    198. Node* minParent = cur;
    199. Node* minRight = cur->_right;
    200. while (minRight->_left)
    201. {
    202. minParent = minRight;
    203. minRight = minRight->_left;
    204. }
    205. swap(minRight->_key, cur->_key); //或cur->_key = minRight->_key;
    206. if (minParent->_left == minRight)
    207. {
    208. minParent->_left = minRight->_right;
    209. }
    210. else
    211. {
    212. minParent->_right = minRight->_right;
    213. }
    214. delete minRight;
    215. 2.使用左子树的最大值结点替代
    216. //Node* maxParent = cur;
    217. //Node* maxLeft = cur->_left;
    218. //while (maxLeft->_right)
    219. //{
    220. // maxParent = maxLeft;
    221. // maxLeft = maxLeft->_right;
    222. //}
    223. //swap(maxLeft->_key, cur->_key); //或cur->_key = maxLeft->_key;
    224. //if (maxParent->_right == maxLeft)
    225. //{
    226. // maxParent->_right = maxLeft->_left;
    227. //}
    228. //else
    229. //{
    230. // maxParent->_left = maxLeft->_left;
    231. //}
    232. //delete maxLeft;
    233. }
    234. return true;
    235. }
    236. }
    237. return false;
    238. }
    239. /
    240. //递归版
    241. //无法直接使用私有成员进行递归,因此嵌套一层成员函数,实现递归
    242. //递归find
    243. Node* FindR(const K& key)
    244. {
    245. return _FindR(_root, key);
    246. }
    247. //递归insert
    248. bool InsertR(const K& key,const V& value)
    249. {
    250. return _InsertR(_root, key,value);
    251. }
    252. //递归erase
    253. bool EraseR(const K& key)
    254. {
    255. return _EraseR(_root, key);
    256. }
    257. private:
    258. //递归insert
    259. bool _InsertR(Node*& root, const K& key,const V& value)
    260. {
    261. //Node*& root这个处理,使得当root为空指针时,但root同时也是父结点的left或right的别名,使得结点得以链接
    262. if (root == nullptr)
    263. {
    264. root = new Node(key,value);
    265. return true;
    266. }
    267. if (root->_key < key)
    268. return _InsertR(root->_right, key,value);
    269. else if (root->_key > key)
    270. return _InsertR(root->_left, key,value);
    271. else
    272. return false;
    273. }
    274. Node* _FindR(Node* root, const K& key) //不允许修改key,但可以修改value,因此可以使用Node*返回
    275. {
    276. if (root == nullptr)
    277. return nullptr;
    278. if (root->_key < key)
    279. {
    280. return _FindR(root->_right, key);
    281. }
    282. else if (root->_key > key)
    283. {
    284. return _FindR(root->_left, key);
    285. }
    286. else
    287. {
    288. return root;
    289. }
    290. }
    291. //递归erase
    292. bool _EraseR(Node*& root, const K& key)
    293. {
    294. if (root == nullptr)
    295. return false;
    296. if (root->_key < key)
    297. {
    298. return _EraseR(root->_right, key);
    299. }
    300. else if (root->_key > key)
    301. {
    302. return _EraseR(root->_left, key);
    303. }
    304. else
    305. {
    306. Node* del = root; //先保存一下
    307. if (root->_left == nullptr)
    308. {
    309. root = root->_right;
    310. }
    311. else if (root->_right == nullptr)
    312. {
    313. root = root->_left;
    314. }
    315. else
    316. {
    317. //1.使用右子树的最小值结点替代
    318. Node* minRight = root->_right;
    319. while (minRight->_left)
    320. {
    321. minRight = minRight->_left;
    322. }
    323. swap(root->_key, minRight->_key);
    324. return _EraseR(root->_right, key);
    325. 2.使用左子树的最大值结点替代
    326. //Node* maxLeft = root->_left;
    327. //while (maxLeft->_right)
    328. //{
    329. // maxLeft = maxLeft->_right;
    330. //}
    331. //swap(root->_key, maxLeft->_key);
    332. //return _EraseR(root->_left, key);
    333. }
    334. delete del;
    335. return true;
    336. }
    337. }
    338. public:
    339. //递归版遍历
    340. void InOrder() //1.中序遍历
    341. {
    342. _InOrder(_root);
    343. cout << endl;
    344. }
    345. void PrevOrder() //2.前序遍历
    346. {
    347. _PrevOrder(_root);
    348. cout << endl;
    349. }
    350. void PostOrder() //3.后序遍历
    351. {
    352. _PostOrder(_root);
    353. cout << endl;
    354. }
    355. private:
    356. //在C语言中,root可以被直接获取,
    357. //在C++中,因为_root 是私有,被封装起来了所以可有以下两种方式获得
    358. //1.可以写一个成员函数GetRoot()获取
    359. //2.也可以使用遍历,不被继承就设为私有成员函数
    360. void _InOrder(Node* root) //1.中序遍历
    361. {
    362. if (root == nullptr)
    363. return;
    364. _InOrder(root->_left);
    365. cout << root->_key << " 出现次数:"<_value<
    366. _InOrder(root->_right);
    367. }
    368. void _PrevOrder(Node* root) //2.前序遍历
    369. {
    370. if (root == nullptr)
    371. return;
    372. //cout << root->_key << " ";
    373. cout << root->_key << " 出现次数:" << root->_value << endl;
    374. _PrevOrder(root->_left);
    375. _PrevOrder(root->_right);
    376. }
    377. void _PostOrder(Node* root) //3.后序遍历
    378. {
    379. if (root == nullptr)
    380. return;
    381. _PostOrder(root->_left);
    382. _PostOrder(root->_right);
    383. //cout << root->_key << " ";
    384. cout << root->_key << " 出现次数:" << root->_value << endl;
    385. }
    386. private:
    387. Node* _root = nullptr; //调用自定义类型Node*
    388. };

    (2)test.cpp:

    1. #include"BSTreeKeyValue.h"
    2. void TestBSTreeKV1()
    3. {
    4. BSTree ECdict; //英文找中文
    5. //使用递归InsertR
    6. /*ECdict.InsertR("hello", "你好");
    7. ECdict.InsertR("world", "世界");*/
    8. //使用非递归Insert
    9. ECdict.Insert("hello", "你好");
    10. ECdict.Insert("world", "世界");
    11. string str;
    12. cout << "请输入要查询的英文单词:" << endl;
    13. while (cin >> str) //原理同while(scanf()!=EOF) //operator>>a
    14. {
    15. 使用递归InsertR
    16. //BSTreeNode*ret= ECdict.FindR(str); //或使用auto
    17. auto ret= ECdict.FindR(str);
    18. //使用非递归Insert
    19. BSTreeNode* ret = ECdict.Find(str); //或使用auto
    20. //auto ret= ECdict.Find(str);
    21. if (ret != nullptr)
    22. {
    23. cout << "对应的中文:" << ret->_value << endl;
    24. cout << "请输入要查询的英文单词:" << endl;
    25. }
    26. else
    27. {
    28. cout << "无此单词,请重新输入!" << endl;
    29. cout << "请输入要查询的英文单词:" << endl;
    30. }
    31. }
    32. }
    33. void TestBSTreeKV2()
    34. {
    35. 1.使用非递归的insert、find
    36. 统计水果出现的次数
    37. //string arr[] = { "苹果", "西瓜", "苹果", "西瓜", "苹果", "苹果", "西瓜",
    38. // "苹果", "香蕉", "苹果", "香蕉" };
    39. //BSTree countTree;
    40. //for (const auto& str : arr)
    41. //{
    42. // // 先查找水果在不在搜索树中
    43. // // 1、不在,说明水果第一次出现,则插入<水果, 1>
    44. // // 2、在,则查找到的节点中水果对应的次数++
    45. // //BSTreeNode* ret = countTree.Find(str);
    46. // auto ret = countTree.Find(str);
    47. // if (ret == NULL)
    48. // {
    49. // countTree.Insert(str, 1);
    50. // }
    51. // else
    52. // {
    53. // ret->_value++;
    54. // }
    55. //}
    56. //countTree.InOrder();
    57. ///*countTree.PrevOrder();
    58. //countTree.PostOrder();*/
    59. //2.使用递归的insert、find
    60. // 统计水果出现的次数
    61. string arr[] = { "苹果", "西瓜", "苹果", "西瓜", "苹果", "苹果", "西瓜",
    62. "苹果", "香蕉", "苹果", "香蕉" };
    63. BSTreeint> countTree;
    64. for (const auto& str : arr)
    65. {
    66. // 先查找水果在不在搜索树中
    67. // 1、不在,说明水果第一次出现,则插入<水果, 1>
    68. // 2、在,则查找到的节点中水果对应的次数++
    69. //BSTreeNode* ret = countTree.FindR(str);
    70. auto ret = countTree.FindR(str);
    71. if (ret == NULL)
    72. {
    73. countTree.InsertR(str, 1);
    74. }
    75. else
    76. {
    77. ret->_value++;
    78. }
    79. }
    80. countTree.InOrder();
    81. /*countTree.PrevOrder();
    82. countTree.PostOrder();*/
    83. }
    84. int main()
    85. {
    86. //TestBSTreeKV1();
    87. TestBSTreeKV2();
    88. return 0;
    89. }

    3.2.5 K、V模型应用举例:

    (1)

    (2)

     

    后记:
    ●由于作者水平有限,文章难免存在谬误之处,敬请读者斧正,俚语成篇,恳望指教!

                                                                           ——By 作者:新晓·故知

     

  • 相关阅读:
    FreeRTOS学习笔记(二)
    豪赌?远见?浙江东方的量子冒险
    c++ SQLite 特别好用的库使用实例-更新(3)
    HTTP 的三次握手
    【Linux】 OpenSSH_7.4p1 升级到 OpenSSH_9.3p1(亲测无问题,建议收藏)
    视频产品介绍:AS-VCVR-N多协议视频接入网关
    Python Number degrees()实例讲解
    JSTL使用
    MySQL5.7版本与8.0版本在Ubuntu(WSL环境)系统安装
    基于ssm大学生社团管理系统
  • 原文地址:https://blog.csdn.net/m0_57859086/article/details/126264869