【C++进阶】二叉树进阶

ゝ一世哀愁。 2024-04-20 06:23 263阅读 0赞

?C++学习历程:入门


  • 博客主页:一起去看日落吗
  • 持续分享博主的C++学习历程
  • 博主的能力有限,出现错误希望大家不吝赐教
  • 分享给大家一句我很喜欢的话: 也许你现在做的事情,暂时看不到成果,但不要忘记,树?成长之前也要扎根,也要在漫长的时光?中沉淀养分。静下来想一想,哪有这么多的天赋异禀,那些让你羡慕的优秀的人也都曾默默地翻山越岭?。

在这里插入图片描述

✨ ⭐️ ? ?


目录

  • ? 1. 二叉搜索树
    • ? 1.1 二叉搜索树概念
    • ? 1.2 二叉搜索树操作
      • ⭐️ 1.2.1 查找
      • ⭐️ 1.2.2 插入
      • ⭐️ 1.2.3 删除
    • ? 1.3 二叉搜索树的实现
      • ⭐️ 1.3.1 BinarySearchTree.hpp
      • ⭐️ 1.3.2 main.cpp
    • ? 1.4 二叉搜索树的应用
      • ⭐️ 1.4.1 _BinarySearchTree.hpp
      • ⭐️ 1.4.2 main.cpp
    • ? 1.5 二叉搜索树的性能分析
  • ? 2. 二叉树OJ题
    • ✨ 第一题
    • ✨ 第二题
    • ✨ 第三题
    • ✨ 第四题
    • ✨ 第五题
    • ✨ 第六题
    • ✨ 第七题
    • ✨ 第八题
    • ✨ 第九题
    • ✨ 第十题

? 1. 二叉搜索树

? 1.1 二叉搜索树概念

二叉搜索树又称二叉排序树,它或者是一棵空树,或者是具有以下性质的二叉树:

  • 若它的左子树不为空,则左子树上所有节点的值都小于根节点的值
  • 若它的右子树不为空,则右子树上所有节点的值都大于根节点的值
  • 它的左右子树也分别为二叉搜索树

在这里插入图片描述


? 1.2 二叉搜索树操作

⭐️ 1.2.1 查找

请添加图片描述

若根节点不为空:

如果 (根节点 key == 查找 key),返回 true;

如果 (根节点 key > 查找 key),在其左子树查找;

如果 (根节点 key < 查找 key),在其右子树查找;

否则,返回 false;

二叉搜索树结构查找一个值最多查找高度次。


⭐️ 1.2.2 插入

插入的具体过程如下:

  • 树为空,则直接新增节点,赋值给root指针
  • 树不空,按二叉搜索树性质查找插入位置,插入新节点

在这里插入图片描述


⭐️ 1.2.3 删除

首先查找元素是否在二叉搜索树中,如果不存在,则返回, 否则要删除的结点可能分下面四种情
况:

  • a. 要删除的结点无孩子结点
  • b. 要删除的结点只有左孩子结点
  • c. 要删除的结点只有右孩子结点
  • d. 要删除的结点有左、右孩子结点

看起来有待删除节点有4中情况,实际情况a可以与情况b或者c合并起来,因此真正的删除过程
如下:

  • 情况b:删除该结点且使被删除节点的双亲结点指向被删除节点的左孩子结点–直接删除
  • 情况c:删除该结点且使被删除节点的双亲结点指向被删除结点的右孩子结点–直接删除
  • 情况d:在它的右子树中寻找中序下的第一个结点(关键码最小),用它的值填补到被删除节点中,再来处理该结点的删除问题–替换法删除

在这里插入图片描述


? 1.3 二叉搜索树的实现

⭐️ 1.3.1 BinarySearchTree.hpp

  1. #pragma once
  2. #include<iostream>
  3. using namespace std;
  4. namespace KEY
  5. {
  6. template<class K>
  7. struct BSTreeNode
  8. {
  9. BSTreeNode<K>* _left;
  10. BSTreeNode<K>* _right;
  11. K _key;
  12. BSTreeNode(const K& key)
  13. : _left(nullptr)
  14. , _right(nullptr)
  15. , _key(key)
  16. {
  17. }
  18. };
  19. template<class K>
  20. class BSTree
  21. {
  22. typedef BSTreeNode<K> Node;
  23. public:
  24. bool Insert(const K& key)
  25. {
  26. //空树,直接插入
  27. if (_root == nullptr)
  28. {
  29. _root = new Node(key);
  30. return true;
  31. }
  32. //查找要插入的位置
  33. Node* parent = nullptr;
  34. Node* cur = _root;
  35. while (cur)
  36. {
  37. if (cur->_key < key)//往右子树查找
  38. {
  39. parent = cur;
  40. cur = cur->_right;
  41. }
  42. else if (cur->_key > key)//往左子树查找
  43. {
  44. parent = cur;
  45. cur = cur->_left;
  46. }
  47. else
  48. {
  49. return false;//默认不支持冗余
  50. }
  51. }
  52. //new节点,这里需要在BSTreeNode补构造函数
  53. cur = new Node(key);
  54. if (parent->_key < cur->_key)//新节点链接到父的左还是右,还需要再比一次
  55. {
  56. parent->_right = cur;//关联
  57. }
  58. else
  59. {
  60. parent->_left = cur;//关联
  61. }
  62. return true;
  63. }
  64. Node* Find(const K& key)
  65. {
  66. Node* cur = _root;
  67. while (cur)
  68. {
  69. if (cur->_key < key)
  70. {
  71. cur = cur->_right;
  72. }
  73. else if (cur->_key > key)
  74. {
  75. cur = cur->_left;
  76. }
  77. else
  78. {
  79. return cur;
  80. }
  81. }
  82. return nullptr;
  83. }
  84. bool Erase(const K& key)
  85. {
  86. Node* parent = nullptr;
  87. Node* cur = _root;
  88. while (cur)
  89. {
  90. if (cur->_key < key)
  91. {
  92. parent = cur;
  93. cur = cur->_right;
  94. }
  95. else if (cur->_key > key)
  96. {
  97. parent = cur;
  98. cur = cur->_left;
  99. }
  100. else
  101. {
  102. //删除
  103. if (cur->_left == nullptr)//ab
  104. {
  105. //没有父亲
  106. if (cur == _root)
  107. {
  108. _root = cur->_right;//右作根
  109. }
  110. else
  111. {
  112. //确定目标位置父亲的左还是右和目标位置的孩子关联(目标位置的左右孩子在外层if已经确定了)
  113. if (cur == parent->_left)
  114. {
  115. parent->_left = cur->_right;
  116. }
  117. else
  118. {
  119. parent->_right = cur->_right;
  120. }
  121. }
  122. delete cur;
  123. }
  124. else if (cur->_right == nullptr)//ac
  125. {
  126. //没有父亲
  127. if (cur == _root)
  128. {
  129. _root = cur->_left;
  130. }
  131. else
  132. {
  133. //确定目标位置父亲的左还是右和目标位置的孩子关联(目标位置的左右孩子在外层if已经确定了)
  134. if (cur == parent->_left)
  135. {
  136. parent->_left = cur->_left;
  137. }
  138. else
  139. {
  140. parent->_right = cur->_left;
  141. }
  142. }
  143. delete cur;
  144. }
  145. else//d
  146. {
  147. //找右树的最小节点去替代删除
  148. Node* minRightParent = cur;
  149. //cur->right一定不为空
  150. Node* minRight = cur->_right;
  151. //最小节点
  152. while (minRight->_left)
  153. {
  154. minRightParent = minRight;
  155. minRight = minRight->_left;
  156. }
  157. //替代
  158. cur->_key = minRight->_key;
  159. //minRight的左一定为空,但右不一定为空,minRightParent->_left不一定是minRight
  160. if (minRight == minRightParent->_left)//删除5,找6
  161. {
  162. minRightParent->_left = minRight->_right;
  163. }
  164. else//删除7,找8
  165. {
  166. minRightParent->_right = minRight->_right;
  167. }
  168. delete minRight;
  169. }
  170. return true;
  171. }
  172. }
  173. return false;
  174. }
  175. void InOrder()
  176. {
  177. _InOrder(_root);
  178. cout << endl;
  179. }
  180. bool InsertR(const K& key)
  181. {
  182. return _InsertR(_root, key);
  183. }
  184. Node* FindR(const K& key)
  185. {
  186. return _FindR(_root, key);
  187. }
  188. bool EraseR(const K& key)
  189. {
  190. return _EraseR(_root, key);
  191. }
  192. //BSTree() = default;//C++11
  193. BSTree()
  194. : _root(nullptr)
  195. {
  196. }
  197. ~BSTree()
  198. {
  199. _Destroy(_root);
  200. }
  201. //BSTree(const BSTree& t)
  202. BSTree(const BSTree<K>& t)
  203. {
  204. _root = _Copy(t._root);
  205. }
  206. //BSTree& operator=(BSTree t)
  207. BSTree<K>& operator=(BSTree<K> t)//现代写法 t1 = t2
  208. {
  209. std::swap(_root, t._root);
  210. return *this;
  211. }
  212. private:
  213. Node* _Copy(Node* root)
  214. {
  215. if (root == nullptr)
  216. {
  217. return nullptr;
  218. }
  219. //深拷贝根
  220. Node* newRoot = new Node(root->_key);
  221. //递归拷贝左右子树
  222. newRoot->_left = _Copy(root->_left);
  223. newRoot->_right = _Copy(root->_right);
  224. //返回根
  225. return newRoot;
  226. }
  227. void _Destroy(Node* root)
  228. {
  229. if (root == nullptr)
  230. {
  231. return;
  232. }
  233. //后序
  234. _Destroy(root->_left);
  235. _Destroy(root->_right);
  236. delete root;
  237. }
  238. bool _EraseR(Node*& root, const K& key)
  239. {
  240. if (root == nullptr)
  241. {
  242. return false;
  243. }
  244. else if (root->_key < key)
  245. {
  246. return _EraseR(root->_right, key);
  247. }
  248. else if (root->_left > key)
  249. {
  250. return _EraseR(root->_left, key);
  251. }
  252. else
  253. {
  254. //删除
  255. Node* del = root;
  256. if (root->_left == nullptr)//ab
  257. {
  258. root = root->_right;
  259. }
  260. else if (root->_right == nullptr)//ac
  261. {
  262. root = root->_left;
  263. }
  264. else//d
  265. {
  266. //替代
  267. Node* minRight = root->_right;
  268. while (minRight->_left)
  269. {
  270. minRight = minRight->_left;
  271. }
  272. root->_key = minRight->_key;
  273. //大事化小,小事化了
  274. return _EraseR(root->_right, minRight->_key);
  275. }
  276. delete del;
  277. return true;
  278. }
  279. }
  280. Node* _FindR(Node* root, const K& key)
  281. {
  282. if (root == nullptr)
  283. {
  284. return nullptr;
  285. }
  286. if (root->_key < key)
  287. {
  288. return _FindR(root->_right, key);
  289. }
  290. else if (root->_key > key)
  291. {
  292. return _FindR(root->_left, key);
  293. }
  294. else
  295. {
  296. return root;
  297. }
  298. }
  299. bool _InsertR(Node*& root, const K& key)
  300. {
  301. if (root == nullptr)
  302. {
  303. root = new Node(key);
  304. return true;
  305. }
  306. else
  307. {
  308. if (root->_key < key)
  309. {
  310. return _InsertR(root->_right, key);
  311. }
  312. else if (root->_key > key)
  313. {
  314. return _InsertR(root->_left, key);
  315. }
  316. else
  317. {
  318. return false;
  319. }
  320. }
  321. }
  322. void _InOrder(Node* root)
  323. {
  324. if (root == nullptr)
  325. {
  326. return;
  327. }
  328. _InOrder(root->_left);
  329. cout << root->_key << " ";
  330. _InOrder(root->_right);
  331. }
  332. private:
  333. Node* _root = nullptr;
  334. };
  335. }

⭐️ 1.3.2 main.cpp

  1. #include "BinarySearchTree.hpp"
  2. void TestBSTree1()
  3. {
  4. int a[] = {
  5. 5, 3, 4, 1, 7, 8, 2, 6, 0, 9 };
  6. KEY::BSTree<int> t;
  7. for (auto e : a)
  8. {
  9. t.Insert(e);
  10. }
  11. t.InOrder();
  12. t.Erase(7);
  13. t.InOrder();
  14. t.Erase(5);
  15. t.InOrder();
  16. }
  17. void TestBSTree2()
  18. {
  19. int a[] = {
  20. 5, 3, 4, 1, 7, 8, 2, 6, 0, 9 };
  21. KEY::BSTree<int> t;
  22. for (auto e : a)
  23. {
  24. t.Insert(e);
  25. }
  26. t.InOrder();
  27. //挨个删除
  28. for (auto e : a)
  29. {
  30. t.Erase(e);
  31. t.InOrder();
  32. }
  33. //先删除左树,再删除根
  34. /*t.Erase(0);
  35. t.Erase(1);
  36. t.Erase(2);
  37. t.Erase(3);
  38. t.Erase(4);
  39. t.Erase(5);
  40. t.InOrder();*/
  41. }
  42. void TestBSTree3()
  43. {
  44. int a[] = {
  45. 5, 3, 4, 1, 7, 8, 2, 6, 0, 9 };
  46. KEY::BSTree<int> t;
  47. for (auto e : a)
  48. {
  49. t.InsertR(e);
  50. }
  51. t.InOrder();
  52. //挨个删除
  53. for (auto e : a)
  54. {
  55. t.Erase(e);
  56. t.InOrder();
  57. }
  58. //先删除左树,再删除根
  59. /*t.Erase(0);
  60. t.Erase(1);
  61. t.Erase(2);
  62. t.Erase(3);
  63. t.Erase(4);
  64. t.Erase(5);
  65. t.InOrder();*/
  66. }
  67. void TestBSTree4()
  68. {
  69. int a[] = {
  70. 5, 3, 4, 1, 7, 8, 2, 6, 0, 9 };
  71. KEY::BSTree<int> t;
  72. for (auto e : a)
  73. {
  74. t.Insert(e);
  75. }
  76. t.InOrder();
  77. KEY::BSTree<int> copy = t;
  78. copy.InOrder();
  79. KEY::BSTree<int> assign;
  80. assign = t;
  81. assign.InOrder();
  82. }
  83. int main()
  84. {
  85. TestBSTree1();
  86. cout << "-------------------" << endl;
  87. TestBSTree2();
  88. cout << "-------------------" << endl;
  89. TestBSTree3();
  90. cout << "-------------------" << endl;
  91. TestBSTree4();
  92. return 0;
  93. }

请添加图片描述


? 1.4 二叉搜索树的应用

  1. K模型:K模型即只有key作为关键码,结构中只需要存储Key即可,关键码即为需要搜索到的值。

比如:给一个单词word,判断该单词是否拼写正确,具体方式如下:

  • 以词库中所有单词集合中的每个单词作为key,构建一棵二叉搜索树
  • 在二叉搜索树中检索该单词是否存在,存在则拼写正确,不存在则拼写错误。
  1. KV模型:每一个关键码key,都有与之对应的值Value,即的键值对。该种方式在现实生活中非常常见:

    • 比如英汉词典就是英文与中文的对应关系,通过英文可以快速找到与其对应的中文,英文单词与其对应的中文就构成一种键值对;
    • 再比如统计单词次数,统计成功后,给定单词就可快速找到其出现的次数,单词与其出现次数就是就构成一种键值对。

⭐️ 1.4.1 _BinarySearchTree.hpp

  1. #pragma once
  2. #include<iostream>
  3. #include<string>
  4. using namespace std;
  5. namespace KEY
  6. {
  7. //...
  8. }
  9. namespace KEY_VALUE
  10. {
  11. template<class K, class V>
  12. struct BSTreeNode
  13. {
  14. BSTreeNode<K, V>* _left;
  15. BSTreeNode<K, V>* _right;
  16. K _key;
  17. V _value;
  18. BSTreeNode(const K& key, const V& value)
  19. : _left(nullptr)
  20. , _right(nullptr)
  21. , _key(key)
  22. , _value(value)
  23. {
  24. }
  25. };
  26. template<class K, class V>
  27. class BSTree
  28. {
  29. typedef BSTreeNode<K, V> Node;
  30. public:
  31. bool Insert(const K& key, const V& value)
  32. {
  33. //空树,直接插入
  34. if (_root == nullptr)
  35. {
  36. _root = new Node(key, value);
  37. return true;
  38. }
  39. //查找要插入的位置
  40. Node* parent = nullptr;
  41. Node* cur = _root;
  42. while (cur)
  43. {
  44. if (cur->_key < key)//往右子树查找
  45. {
  46. parent = cur;
  47. cur = cur->_right;
  48. }
  49. else if (cur->_key > key)//往左子树查找
  50. {
  51. parent = cur;
  52. cur = cur->_left;
  53. }
  54. else
  55. {
  56. return false;//默认不支持冗余
  57. }
  58. }
  59. //new节点,这里需要在BSTreeNode补构造函数
  60. cur = new Node(key, value);
  61. if (parent->_key < cur->_key)//新节点链接到父的左还是右,还需要再比一次
  62. {
  63. parent->_right = cur;//关联
  64. }
  65. else
  66. {
  67. parent->_left = cur;//关联
  68. }
  69. return true;
  70. }
  71. Node* Find(const K& key)
  72. {
  73. Node* cur = _root;
  74. while (cur)
  75. {
  76. if (cur->_key < key)
  77. {
  78. cur = cur->_right;
  79. }
  80. else if (cur->_key > key)
  81. {
  82. cur = cur->_left;
  83. }
  84. else
  85. {
  86. return cur;
  87. }
  88. }
  89. return nullptr;
  90. }
  91. bool Erase(const K& key)
  92. {
  93. Node* parent = nullptr;
  94. Node* cur = _root;
  95. while (cur)
  96. {
  97. if (cur->_key < key)
  98. {
  99. parent = cur;
  100. cur = cur->_right;
  101. }
  102. else if (cur->_key > key)
  103. {
  104. parent = cur;
  105. cur = cur->_left;
  106. }
  107. else
  108. {
  109. //删除
  110. if (cur->_left == nullptr)//ab
  111. {
  112. //没有父亲
  113. if (cur == _root)
  114. {
  115. _root = cur->_right;//右作根
  116. }
  117. else
  118. {
  119. //确定目标位置父亲的左还是右和目标位置的孩子关联(目标位置的左右孩子在外层if已经确定了)
  120. if (cur == parent->_left)
  121. {
  122. parent->_left = cur->_right;
  123. }
  124. else
  125. {
  126. parent->_right = cur->_right;
  127. }
  128. }
  129. delete cur;
  130. }
  131. else if (cur->_right == nullptr)//ac
  132. {
  133. //没有父亲
  134. if (cur == _root)
  135. {
  136. _root = cur->_left;
  137. }
  138. else
  139. {
  140. //确定目标位置父亲的左还是右和目标位置的孩子关联(目标位置的左右孩子在外层if已经确定了)
  141. if (cur == parent->_left)
  142. {
  143. parent->_left = cur->_left;
  144. }
  145. else
  146. {
  147. parent->_right = cur->_left;
  148. }
  149. }
  150. delete cur;
  151. }
  152. else//d
  153. {
  154. //找右树的最小节点去替代删除
  155. Node* minRightParent = cur;
  156. //cur->right一定不为空
  157. Node* minRight = cur->_right;
  158. //最小节点
  159. while (minRight->_left)
  160. {
  161. minRightParent = minRight;
  162. minRight = minRight->_left;
  163. }
  164. //替代
  165. cur->_key = minRight->_key;
  166. //minRight的左一定为空,但右不一定为空,minRightParent->_left不一定是minRight
  167. if (minRight == minRightParent->_left)//删除5,找6
  168. {
  169. minRightParent->_left = minRight->_right;
  170. }
  171. else//删除7,找8
  172. {
  173. minRightParent->_right = minRight->_right;
  174. }
  175. delete minRight;
  176. }
  177. return true;
  178. }
  179. }
  180. return false;
  181. }
  182. void InOrder()
  183. {
  184. _InOrder(_root);
  185. cout << endl;
  186. }
  187. private:
  188. void _InOrder(Node* root)
  189. {
  190. if (root == nullptr)
  191. {
  192. return;
  193. }
  194. _InOrder(root->_left);
  195. cout << root->_key << ":" << root->_value << endl;
  196. _InOrder(root->_right);
  197. }
  198. private:
  199. Node* _root = nullptr;
  200. };
  201. }

⭐️ 1.4.2 main.cpp

  1. #include"_BinarySearchTree.hpp"
  2. void TestBSTree1()
  3. {
  4. KEY_VALUE::BSTree<string, string> dict;
  5. dict.Insert("sort", "排序");
  6. dict.Insert("insert", "插入");
  7. dict.Insert("tree", "树");
  8. dict.Insert("left", "左边");
  9. dict.Insert("right", "右边");
  10. //...
  11. string str;
  12. while(cin >> str)
  13. {
  14. if(str == "Q")
  15. {
  16. break;
  17. }
  18. else
  19. {
  20. auto ret = dict.Find(str);
  21. if(ret == nullptr)
  22. {
  23. cout << "拼写错误,请检查你的单词" << endl;
  24. }
  25. else
  26. {
  27. cout << ret->_key << "->" << ret->_value << endl;
  28. }
  29. }
  30. }
  31. }
  32. void TestBSTree2()
  33. {
  34. string str[] = {
  35. "sort", "sort", "tree", "insert", "sort", "tree", "sort", "test", "sort" };
  36. KEY_VALUE::BSTree<string, int> countTree;
  37. for(auto& e : str)
  38. {
  39. auto ret = countTree.Find(e);
  40. if(ret == nullptr)
  41. {
  42. countTree.Insert(e, 1);//第一次出现
  43. }
  44. else
  45. {
  46. ret->_value++;//非第一次出现
  47. }
  48. }
  49. countTree.InOrder();
  50. }
  51. int main()
  52. {
  53. TestBSTree1();
  54. TestBSTree2();
  55. return 0;
  56. }

请添加图片描述


? 1.5 二叉搜索树的性能分析

插入和删除操作都必须先查找,查找效率代表了二叉搜索树中各个操作的性能。

对有n个结点的二叉搜索树,若每个元素查找的概率相等,则二叉搜索树平均查找长度是结点在二叉搜索树的深度的函数,即结点越深,则比较次数越多。

但对于同一个关键码集合,如果各关键码插入的次序不同,可能得到不同结构的二叉搜索树:

在这里插入图片描述

  • 最优情况下,二叉搜索树为完全二叉树(或者接近完全二叉树)
  • 最差情况下,二叉搜索树退化为单支树(或者类似单支)

问题:如果退化成单支树,二叉搜索树的性能就失去了。那能否进行改进,不论按照什么次序插入关键码,二叉搜索树的性能都能达到最优?那么我们学习的AVL树和红黑树就可以上场了。


? 2. 二叉树OJ题

✨ 第一题

链接:根据二叉树创建字符串

在这里插入图片描述
请添加图片描述

解题思路

我们可以使用递归的方法得到二叉树的前序遍历,并在递归时加上额外的括号。

会有以下 4 种情况:

  • 如果当前节点有两个孩子,那我们在递归时,需要在两个孩子的结果外都加上一层括号;
  • 如果当前节点没有孩子,那我们不需要在节点后面加上任何括号;

请添加图片描述
如果当前节点只有左孩子,那我们在递归时,只需要在左孩子的结果外加上一层括号,而不需要给右孩子加上任何括号;

请添加图片描述

如果当前节点只有右孩子,那我们在递归时,需要先加上一层空的括号 ‘()’\text{`()’}‘()’ 表示左孩子为空,再对右孩子进行递归,并在结果外加上一层括号。

请添加图片描述


代码演示

  1. class Solution {
  2. public:
  3. string tree2str(TreeNode* root) {
  4. if(root == nullptr)
  5. return "";
  6. if(root -> left == nullptr && root -> right == nullptr)
  7. return to_string(root -> val);
  8. if(root -> right == nullptr)
  9. return to_string(root -> val) + '(' + tree2str(root -> left) + ')';
  10. return to_string(root -> val) + '(' + tree2str(root -> left) + ')' + '(' + tree2str(root -> right) + ')';
  11. }
  12. };

✨ 第二题

链接:二叉树的层序遍历1

在这里插入图片描述

解题思路

按层打印: 题目要求的二叉树的 从上至下 打印(即按层打印),又称为二叉树的 广度优先搜索(BFS)。BFS 通常借助 队列 的先入先出特性来实现。 II. 每层打印到一行: 将本层全部节点打印到一行,并将下一层全部节点加入队列,以此类推,即可分为多行打印。

算法流程

  • 特例处理: 当根节点为空,则返回空列表 [] ;
  • 初始化: 打印结果列表 res = [] ,包含根节点的队列 queue = [root] ;
  • BFS 循环: 当队列 queue 为空时跳出;
  • 大小:计算队列的大小也就是当前根结点有多少孩子结点;
  • 新建一个临时列表 tmp ,用于存储当前层打印结果;
  • 当前层打印循环: 循环次数为当前层节点数(即队列 queue 长度);
  • 出队: 队首元素出队,记为 node;
  • 打印: 将 node.val 添加至 tmp 尾部;
  • 添加子节点: 若 node 的左(右)子节点不为空,则将左(右)子节点加入队列 queue ;
  • 将当前层结果 tmp 添加入 res 。
  • 返回值: 返回打印结果列表 res 即可。

代码演示:

  1. class Solution {
  2. public:
  3. vector<vector<int>> levelOrder(TreeNode* root) {
  4. vector<vector<int>> res;
  5. queue<TreeNode*> q;
  6. if(root != nullptr)
  7. q.push(root);
  8. //开始遍历
  9. while(!q.empty())
  10. {
  11. int size = q.size();
  12. vector<int> vec;
  13. for(int i = 0;i < size;i++)
  14. {
  15. TreeNode* node = q.front();//第一个节点
  16. q.pop();
  17. vec.push_back(node -> val);
  18. if(node -> left != nullptr)
  19. q.push(node -> left);
  20. if(node -> right != nullptr)
  21. q.push(node -> right);
  22. }
  23. //保存数据
  24. res.push_back(vec);
  25. }
  26. return res;
  27. }
  28. };

✨ 第三题

链接:二叉树的层序遍历2

请添加图片描述

解题思路

很简单,正着遍历一遍然后reveres反过来就可以了

代码演示

  1. class Solution {
  2. public:
  3. vector<vector<int>> levelOrderBottom(TreeNode* root) {
  4. vector<vector<int>> res;
  5. queue<TreeNode*> q;
  6. if(root != nullptr)
  7. q.push(root);
  8. //开始遍历
  9. while(!q.empty())
  10. {
  11. int size = q.size();
  12. vector<int> vec;
  13. for(int i = 0;i < size;i++)
  14. {
  15. TreeNode* node = q.front();//第一个节点
  16. q.pop();
  17. vec.push_back(node -> val);
  18. if(node -> left != nullptr)
  19. q.push(node -> left);
  20. if(node -> right != nullptr)
  21. q.push(node -> right);
  22. }
  23. //保存数据
  24. res.push_back(vec);
  25. }
  26. reverse(res.begin(),res.end());//反转
  27. return res;
  28. }
  29. };

✨ 第四题

链接:二叉树最近的公共祖先

请添加图片描述

请添加图片描述

解题思路

根据定义,若 rootrootroot 是 p,qp, qp,q 的 最近公共祖先 ,则只可能为以下情况之一:

  • p 和 q 在 roott 的子树中,且分列 root 的 异侧(即分别在左、右子树中);
  • p=root ,且 q 在 root 的左或右子树中;
  • q=root ,且 p 在 root 的左或右子树中;

代码演示

  1. class Solution {
  2. public:
  3. TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  4. if(root == nullptr || root == p || root == q)
  5. return root;
  6. TreeNode *left = lowestCommonAncestor(root -> left ,p ,q);
  7. TreeNode *right = lowestCommonAncestor(root -> right ,p ,q);
  8. if(left == nullptr)
  9. return right;
  10. if(right == nullptr)
  11. return left;
  12. return root;
  13. }
  14. };

✨ 第五题

链接:二叉搜索树和双向链表

请添加图片描述

请添加图片描述

解题思路

二叉搜索树最左端的元素一定最小,最右端的元素一定最大,符合“左中右”的特性,因此二叉搜索树的中序遍历就是一个递增序列,我们只要对它中序遍历就可以组装称为递增双向链表。

代码演示

  1. class Solution {
  2. public:
  3. TreeNode* head = nullptr;
  4. TreeNode* prev = nullptr;
  5. TreeNode* Convert(TreeNode* pRootOfTree) {
  6. if(pRootOfTree == nullptr)
  7. return nullptr;
  8. Convert(pRootOfTree -> left);
  9. if(prev == nullptr)
  10. {
  11. head = pRootOfTree;
  12. prev = pRootOfTree;
  13. }
  14. else
  15. {
  16. prev -> right = pRootOfTree;
  17. pRootOfTree -> left = prev;
  18. prev = pRootOfTree;
  19. }
  20. Convert(pRootOfTree -> right);
  21. return head;
  22. }
  23. };

✨ 第六题

链接:从前序与中序遍历序列构造二叉树

请添加图片描述

解题思路:

只要我们在中序遍历中定位到根节点,那么我们就可以分别知道左子树和右子树中的节点数目。由于同一颗子树的前序遍历和中序遍历的长度显然是相同的,因此我们就可以对应到前序遍历的结果中,对上述形式中的所有左右括号进行定位。

这样以来,我们就知道了左子树的前序遍历和中序遍历结果,以及右子树的前序遍历和中序遍历结果,我们就可以递归地对构造出左子树和右子树,再将这两颗子树接到根节点的左右位置。

代码演示:

  1. class Solution {
  2. public:
  3. TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
  4. // 若节点个数等于0
  5. if(preorder.size() == 0){
  6. return nullptr;
  7. }
  8. // 先序遍历的第一个节点 preorder[0] 为 根节点 root
  9. TreeNode* root = new TreeNode(preorder[0]);
  10. stack<TreeNode*> s;
  11. // 将根节点入栈
  12. s.push(root);
  13. // 初始化扫描中序遍历的指针
  14. int idx = 0;
  15. for(int i = 1; i < preorder.size(); i++){
  16. TreeNode* node = s.top();
  17. // 若 栈顶元素的值 与 中序遍历当前所指的值 不相同
  18. // 表明当前节点存在子树
  19. if(node->val != inorder[idx]){
  20. node->left = new TreeNode(preorder[i]);
  21. s.push(node->left);
  22. }
  23. // 若 栈顶元素的值 与 中序遍历当前所指的值 相同
  24. // 表明当前节点不存在子树,即为最左下角的节点
  25. else{
  26. // 当 栈非空 且 栈顶元素的值 与 中序遍历当前所指的值 相同
  27. while(!s.empty() && s.top()->val == inorder[idx]){
  28. // 指针向右扫描中序遍历
  29. node = s.top();
  30. // 弹出栈中所有与当前指针所指元素值相同的节点
  31. s.pop();
  32. // 中序遍历指针向右移动
  33. idx++;
  34. }
  35. // while循环结束后,当前node所指向的节点就是需要重建右子树的节点
  36. node->right = new TreeNode(preorder[i]);
  37. s.push(node->right);
  38. }
  39. }
  40. return root;
  41. }
  42. };

✨ 第七题

链接:从中序与后序遍历构造二叉树

请添加图片描述

解题思路

首先解决这道题我们需要明确给定一棵二叉树,我们是如何对其进行中序遍历与后序遍历的:

中序遍历的顺序是每次遍历左孩子,再遍历根节点,最后遍历右孩子。
后序遍历的顺序是每次遍历左孩子,再遍历右孩子,最后遍历根节点。

代码演示

  1. class Solution {
  2. int post_idx;
  3. unordered_map<int, int> idx_map;
  4. public:
  5. TreeNode* helper(int in_left, int in_right, vector<int>& inorder, vector<int>& postorder){
  6. // 如果这里没有节点构造二叉树了,就结束
  7. if (in_left > in_right) {
  8. return nullptr;
  9. }
  10. // 选择 post_idx 位置的元素作为当前子树根节点
  11. int root_val = postorder[post_idx];
  12. TreeNode* root = new TreeNode(root_val);
  13. // 根据 root 所在位置分成左右两棵子树
  14. int index = idx_map[root_val];
  15. // 下标减一
  16. post_idx--;
  17. // 构造右子树
  18. root->right = helper(index + 1, in_right, inorder, postorder);
  19. // 构造左子树
  20. root->left = helper(in_left, index - 1, inorder, postorder);
  21. return root;
  22. }
  23. TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
  24. // 从后序遍历的最后一个元素开始
  25. post_idx = (int)postorder.size() - 1;
  26. // 建立(元素,下标)键值对的哈希表
  27. int idx = 0;
  28. for (auto& val : inorder) {
  29. idx_map[val] = idx++;
  30. }
  31. return helper(0, (int)inorder.size() - 1, inorder, postorder);
  32. }
  33. };

✨ 第八题

链接:二叉树的前序遍历

请添加图片描述

请添加图片描述

解题思路:

首先我们需要了解什么是二叉树的前序遍历:按照访问根节点——左子树——右子树的方式遍历这棵树,而在访问左子树或者右子树的时候,我们按照同样的方式遍历,直到遍历完整棵树。因此整个遍历过程天然具有递归的性质,我们可以直接用递归函数来模拟这一过程。

定义 preorder(root) 表示当前遍历到 root 节点的答案。按照定义,我们只要首先将 root 节点的值加入答案,然后递归调用 preorder(root.left) 来遍历 root 节点的左子树,最后递归调用preorder(root.right) 来遍历 root 节点的右子树即可,递归终止的条件为碰到空节点。

代码演示:

  1. class Solution {
  2. public:
  3. vector<int> preorderTraversal(TreeNode* root) {
  4. vector<int> res;
  5. if(root == nullptr)
  6. return res;
  7. stack<TreeNode*> stk;
  8. TreeNode* node = root;
  9. while(!stk.empty() || node != nullptr)
  10. {
  11. while(node != nullptr)
  12. {
  13. res.push_back(node -> val);
  14. stk.push(node);
  15. node = node -> left;
  16. }
  17. node = stk.top();
  18. stk.pop();
  19. node = node -> right;
  20. }
  21. return res;
  22. }
  23. };

✨ 第九题

链接:二叉树的中序遍历

请添加图片描述

解题思路

和前序遍历思路差不多

代码演示

  1. class Solution {
  2. public:
  3. vector<int> inorderTraversal(TreeNode* root) {
  4. vector<int> res;
  5. stack<TreeNode*> stk;
  6. while (root != nullptr || !stk.empty()) {
  7. while (root != nullptr) {
  8. stk.push(root);
  9. root = root->left;
  10. }
  11. root = stk.top();
  12. stk.pop();
  13. res.push_back(root->val);
  14. root = root->right;
  15. }
  16. return res;
  17. }
  18. };

✨ 第十题

链接:二叉树的后续遍历

请添加图片描述

解题思路

我们也可以用迭代的方式实现方法一的递归函数,两种方式是等价的,区别在于递归的时候隐式地维护了一个栈,而我们在迭代的时候需要显式地将这个栈模拟出来,其余的实现与细节都相同,具体可以参考下面的代码。

代码演示

  1. class Solution {
  2. public:
  3. vector<int> postorderTraversal(TreeNode *root) {
  4. vector<int> res;
  5. if (root == nullptr) {
  6. return res;
  7. }
  8. stack<TreeNode *> stk;
  9. TreeNode *prev = nullptr;
  10. while (root != nullptr || !stk.empty()) {
  11. while (root != nullptr) {
  12. stk.emplace(root);
  13. root = root->left;
  14. }
  15. root = stk.top();
  16. stk.pop();
  17. if (root->right == nullptr || root->right == prev) {
  18. res.emplace_back(root->val);
  19. prev = root;
  20. root = nullptr;
  21. } else {
  22. stk.emplace(root);
  23. root = root->right;
  24. }
  25. }
  26. return res;
  27. }
  28. };

发表评论

表情:
评论列表 (有 0 条评论,263人围观)

还没有评论,来说两句吧...

相关阅读

    相关 c++之版】

    前言 在c语言阶段的数据结构系列中已经学习过二叉树,但是这篇文章是二叉树的进阶版,因为首先就会讲到一种树形结构“二叉搜索树”,学习二叉搜索树的目标是为了更好的理解map和