代码随想录算法训练营第二十一天 | 235. 二叉搜索树的最近公共祖先,701.二叉搜索树中的插入操作,450.删除二叉搜索树中的节点

一、参考资料

二叉搜索树的最近公共祖先

题目链接/文章讲解:https://programmercarl.com/0235.%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E7%9A%84%E6%9C%80%E8%BF%91%E5%85%AC%E5%85%B1%E7%A5%96%E5%85%88.html

视频讲解:https://www.bilibili.com/video/BV1Zt4y1F7ww

二叉搜索树中的插入操作

题目链接/文章讲解:https://programmercarl.com/0701.%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E4%B8%AD%E7%9A%84%E6%8F%92%E5%85%A5%E6%93%8D%E4%BD%9C.html

视频讲解:https://www.bilibili.com/video/BV1Et4y1c78Y

删除二叉搜索树中的节点

题目链接/文章讲解:https://programmercarl.com/0450.%E5%88%A0%E9%99%A4%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E4%B8%AD%E7%9A%84%E8%8A%82%E7%82%B9.html

视频讲解:https://www.bilibili.com/video/BV1tP41177us

二、LeetCode235. 二叉搜索树的最近公共祖先

https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/description/

给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大( 一个节点也可以是它自己的祖先)。”
例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5]【如上图】

示例 1:
输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
输出: 6
解释: 节点 2 和节点 8 的最近公共祖先是 6。
示例 2:
输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
输出: 2
解释: 节点 2 和节点 4 的最近公共祖先是 2, 因为根据定义最近公共祖先节点可以为节点本身。

说明:
所有节点的值都是唯一的。
p、q 为不同节点且均存在于给定的二叉搜索树中。
  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. // version1:递归版
  11. class Solution {
  12. public:
  13. TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  14. if (root == NULL) return NULL;
  15. // 左
  16. if (root->val > p->val && root->val > q->val) {
  17. TreeNode* left = lowestCommonAncestor(root->left, p, q);
  18. if (left != NULL) return left;
  19. }
  20. // 右
  21. if (root->val < p->val && root->val < q->val) {
  22. TreeNode* right = lowestCommonAncestor(root->right, p, q);
  23. if (right != NULL) return right;
  24. }
  25. // 一边大一边小,当前节点在p和q中间,或者等于p,或者等于q
  26. return root;
  27. }
  28. };
  1. // version2:递归精简版
  2. class Solution {
  3. public:
  4. TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  5. if (root == NULL) return NULL;
  6. if (root->val > p->val && root->val > q->val) {
  7. return lowestCommonAncestor(root->left, p, q);
  8. }
  9. if (root->val < p->val && root->val < q->val) {
  10. return lowestCommonAncestor(root->right, p, q);
  11. }
  12. return root;
  13. }
  14. };

迭代法:

  1. // version3:迭代版
  2. class Solution {
  3. public:
  4. TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  5. while (root) {
  6. if (root->val > p->val && root->val > q->val) {
  7. root = root->left;
  8. } else if (root->val < p->val && root->val < q->val) {
  9. root = root->right;
  10. } else return root;
  11. }
  12. return NULL;
  13. }
  14. };

三、LeetCode701.二叉搜索树中的插入操作

https://leetcode.cn/problems/insert-into-a-binary-search-tree/description/

示例1:

示例一的另一个图

给定二叉搜索树(BST)的根节点 root 和要插入树中的值 value ,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据 保证 ,新值和原始二叉搜索树中的任意节点值都不同。
注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回 任意有效的结果

示例 1:
输入:root = [4,2,7,1,3], val = 5 输出:[4,2,7,1,3,5] 解释:另一个满足题目要求可以通过的树是: 【如上图】

示例 2:
输入:root = [40,20,60,10,30,50,70], val = 25 输出:[40,20,60,10,30,50,70,null,null,25]
示例 3:
输入:root = [4,2,7,1,3,null,null,null,null,null,null], val = 5 输出:[4,2,7,1,3,5]
提示:
树中的节点数将在 [0, 10^4]的范围内。
-10^8 <= Node.val <= 10^8
所有值 Node.val 是 独一无二 的。
-10^8 <= val <= 10^8
保证 val 在原始BST中不存在。
  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10. * };
  11. */
  12. // version1:递归法,每次的节点都插入到叶子节点的位置
  13. class Solution {
  14. public:
  15. TreeNode* insertIntoBST(TreeNode* root, int val) {
  16. // 找到了插入的位置
  17. if (root == NULL) {
  18. TreeNode* node = new TreeNode(val);
  19. return node;
  20. } else if (root->val > val) {
  21. root->left = insertIntoBST(root->left, val);
  22. } else {
  23. root->right = insertIntoBST(root->right, val);
  24. }
  25. return root;
  26. }
  27. };

迭代法:【参考卡哥文章讲解】

  1. class Solution {
  2. public:
  3. TreeNode* insertIntoBST(TreeNode* root, int val) {
  4. if (root == NULL) {
  5. TreeNode* node = new TreeNode(val);
  6. return node;
  7. }
  8. TreeNode* cur = root;
  9. TreeNode* parent = root; // 这个很重要,需要记录上一个节点,否则无法赋值新节点
  10. while (cur != NULL) {
  11. parent = cur;
  12. if (cur->val > val) cur = cur->left;
  13. else cur = cur->right;
  14. }
  15. TreeNode* node = new TreeNode(val);
  16. if (val < parent->val) parent->left = node;// 此时是用parent节点的进行赋值
  17. else parent->right = node;
  18. return root;
  19. }
  20. };

注意本身递归的过程就有优化,迭代的方法就需要记录当前遍历节点的父节点了,这个和没有返回值的递归函数实现的代码逻辑是一样的,而递归是不需要,因为它直接返回了,与刚刚插入的节点正好完成了衔接。

四、LeetCode450.删除二叉搜索树中的节点

https://leetcode.cn/problems/delete-node-in-a-bst/description/

示例一:

给定一个二叉搜索树的根节点 root 和一个值 key,删除二叉搜索树中的 key 对应的节点,并保证二叉搜索树的性质不变。返回二叉搜索树(有可能被更新)的根节点的引用。
一般来说,删除节点可分为两个步骤:
首先找到需要删除的节点;
如果找到了,删除它。

示例 1:

输入:root = [5,3,6,2,4,null,7], key = 3 输出:[5,4,6,2,null,null,7] 解释:给定需要删除的节点值是 3,所以我们首先找到 3 这个节点,然后删除它。 一个正确的答案是 [5,4,6,2,null,null,7], 如下图所示。 另一个正确答案是 [5,2,6,null,4,null,7]。
示例 2:
输入: root = [5,3,6,2,4,null,7], key = 0 输出: [5,3,6,2,4,null,7] 解释: 二叉树不包含值为 0 的节点
示例 3:
输入: root = [], key = 0 输出: []

提示:
节点数的范围 [0, 10^4].
-10^5 <= Node.val <= 10^5
节点值唯一
root 是合法的二叉搜索树
-10^5 <= key <= 10^5

进阶: 要求算法时间复杂度为 O(h),h 为树的高度。
  1. // 我根据视频讲解思路理解写的代码:
  2. /**
  3. * Definition for a binary tree node.
  4. * struct TreeNode {
  5. * int val;
  6. * TreeNode *left;
  7. * TreeNode *right;
  8. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  10. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  11. * };
  12. */
  13. //看视频听懂了思路,我来写写试试。一共有五种情况(左空右空,左不空右空,左空右不空,左不空右不空)
  14. class Solution {
  15. public:
  16. TreeNode* deleteNode(TreeNode* root, int key) {
  17. if (root == NULL) return NULL;
  18. if (root->val == key) {
  19. if (!root->left && !root->right) {
  20. return NULL;
  21. } else if (root->left && !root->right) {
  22. return root->left;
  23. } else if (!root->left && root->right) {
  24. return root->right;
  25. } else {
  26. TreeNode* cur = root->right;
  27. while (cur->left) cur = cur->left;
  28. cur->left = root->left;
  29. return root->right;
  30. }
  31. }
  32. if (root->val > key) root->left = deleteNode(root->left, key);
  33. if (root->val < key) root->right = deleteNode(root->right, key);
  34. return root;
  35. }
  36. };
  1. // 稍微简化一些
  2. /**
  3. * Definition for a binary tree node.
  4. * struct TreeNode {
  5. * int val;
  6. * TreeNode *left;
  7. * TreeNode *right;
  8. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  10. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  11. * };
  12. */
  13. //看视频听懂了思路,我来写写试试。一共有五种情况(左空右空,左不空右空,左空右不空,左不空右不空)
  14. class Solution {
  15. public:
  16. TreeNode* deleteNode(TreeNode* root, int key) {
  17. if (root == NULL) return NULL;
  18. if (root->val == key) {
  19. if (!root->left && !root->right) return NULL;
  20. else if (root->left && !root->right) return root->left;
  21. else if (!root->left && root->right) return root->right;
  22. else {
  23. TreeNode* cur = root->right;
  24. while (cur->left) cur = cur->left;
  25. cur->left = root->left;
  26. return root->right;
  27. }
  28. }
  29. if (root->val > key) root->left = deleteNode(root->left, key);
  30. if (root->val < key) root->right = deleteNode(root->right, key);
  31. return root;
  32. }
  33. };

卡哥文章详解——五种情况的具体分析:

  • 第一种情况:没找到删除的节点,遍历到空节点直接返回了

  • 找到删除的节点

  • 第二种情况:左右孩子都为空(叶子节点),直接删除节点, 返回NULL为根节点

  • 第三种情况:删除节点的左孩子为空,右孩子不为空,删除节点,右孩子补位,返回右孩子为根节点

  • 第四种情况:删除节点的右孩子为空,左孩子不为空,删除节点,左孩子补位,返回左孩子为根节点

  • 第五种情况:左右孩子节点都不为空,则将删除节点的左子树头结点(左孩子)放到删除节点的右子树的最左面节点的左孩子上,返回删除节点右孩子为新的根节点。

对应注释版本代码

  1. class Solution {
  2. public:
  3. TreeNode* deleteNode(TreeNode* root, int key) {
  4. if (root == nullptr) return root; // 第一种情况:没找到删除的节点,遍历到空节点直接返回了
  5. if (root->val == key) {
  6. // 第二种情况:左右孩子都为空(叶子节点),直接删除节点, 返回NULL为根节点
  7. if (root->left == nullptr && root->right == nullptr) {
  8. ///! 内存释放
  9. delete root;
  10. return nullptr;
  11. }
  12. // 第三种情况:其左孩子为空,右孩子不为空,删除节点,右孩子补位 ,返回右孩子为根节点
  13. else if (root->left == nullptr) {
  14. auto retNode = root->right;
  15. ///! 内存释放
  16. delete root;
  17. return retNode;
  18. }
  19. // 第四种情况:其右孩子为空,左孩子不为空,删除节点,左孩子补位,返回左孩子为根节点
  20. else if (root->right == nullptr) {
  21. auto retNode = root->left;
  22. ///! 内存释放
  23. delete root;
  24. return retNode;
  25. }
  26. // 第五种情况:左右孩子节点都不为空,则将删除节点的左子树放到删除节点的右子树的最左面节点的左孩子的位置
  27. // 并返回删除节点右孩子为新的根节点。
  28. else {
  29. TreeNode* cur = root->right; // 找右子树最左面的节点
  30. while(cur->left != nullptr) {
  31. cur = cur->left;
  32. }
  33. cur->left = root->left; // 把要删除的节点(root)左子树放在cur的左孩子的位置
  34. TreeNode* tmp = root; // 把root节点保存一下,下面来删除
  35. root = root->right; // 返回旧root的右孩子作为新root
  36. delete tmp; // 释放节点内存(这里不写也可以,但C++最好手动释放一下吧)
  37. return root;
  38. }
  39. }
  40. if (root->val > key) root->left = deleteNode(root->left, key);
  41. if (root->val < key) root->right = deleteNode(root->right, key);
  42. return root;
  43. }
  44. };

迭代法:(这个题的迭代法没有做过多研究)

  1. class Solution {
  2. private:
  3. // 将目标节点(删除节点)的左子树放到 目标节点的右子树的最左面节点的左孩子位置上
  4. // 并返回目标节点右孩子为新的根节点
  5. // 是动画里模拟的过程
  6. TreeNode* deleteOneNode(TreeNode* target) {
  7. if (target == nullptr) return target;
  8. if (target->right == nullptr) return target->left;
  9. TreeNode* cur = target->right;
  10. while (cur->left) {
  11. cur = cur->left;
  12. }
  13. cur->left = target->left;
  14. return target->right;
  15. }
  16. public:
  17. TreeNode* deleteNode(TreeNode* root, int key) {
  18. if (root == nullptr) return root;
  19. TreeNode* cur = root;
  20. TreeNode* pre = nullptr; // 记录cur的父节点,用来删除cur
  21. while (cur) {
  22. if (cur->val == key) break;
  23. pre = cur;
  24. if (cur->val > key) cur = cur->left;
  25. else cur = cur->right;
  26. }
  27. if (pre == nullptr) { // 如果搜索树只有头结点
  28. return deleteOneNode(cur);
  29. }
  30. // pre 要知道是删左孩子还是右孩子
  31. if (pre->left && pre->left->val == key) {
  32. pre->left = deleteOneNode(cur);
  33. }
  34. if (pre->right && pre->right->val == key) {
  35. pre->right = deleteOneNode(cur);
  36. }
  37. return root;
  38. }
  39. };

普通二叉树的删除方式

通用的删除,普通二叉树的删除方式(没有使用搜索树的特性,遍历整棵树),用交换值的操作来删除目标节点。

代码中目标节点(要删除的节点)被操作了两次:

  • 第一次是和目标节点的右子树最左面节点交换。

  • 第二次直接被NULL覆盖了。

代码如下:

  1. class Solution {
  2. public:
  3. TreeNode* deleteNode(TreeNode* root, int key) {
  4. if (root == nullptr) return root;
  5. if (root->val == key) {
  6. if (root->right == nullptr) { // 这里第二次操作目标值:最终删除的作用
  7. return root->left;
  8. }
  9. TreeNode *cur = root->right;
  10. while (cur->left) {
  11. cur = cur->left;
  12. }
  13. swap(root->val, cur->val); // 这里第一次操作目标值:交换目标值其右子树最左面节点。
  14. }
  15. root->left = deleteNode(root->left, key);
  16. root->right = deleteNode(root->right, key);
  17. return root;
  18. }
  19. };

卡哥总结:

二叉搜索树删除节点比增加节点复杂的多。

因为二叉搜索树添加节点只需要在叶子上添加就可以的,不涉及到结构的调整,而删除节点操作涉及到结构的调整

这里我们依然使用递归函数的返回值来完成把节点从二叉树中移除的操作。

这里最关键的逻辑就是第五种情况(删除一个左右孩子都不为空的节点),这种情况一定要想清楚

而且就算想清楚了,对应的代码也未必可以写出来,所以这道题目既考察思维逻辑,也考察代码能力

递归中我给出了两种写法,推荐大家学会第一种(利用搜索树的特性)就可以了,第二种递归写法其实是比较绕的。【第二种指普通二叉树的删除节点】


总结:

博客补完了!成就感up,继续加油叭~还剩最后一天树的题目,一鼓作气写完,木有休息的休息日哈哈哈,不过是值得的,总算是赶上了进度。

posted @ 2023-02-05 17:15  ZYM-爱吃柚子的程序媛  阅读(370)  评论(0)    收藏  举报