2024-03-27
Go & Python & 算法
00

目录

1 LeetCode235 二叉搜索树的最近公共祖先
2 LeetCode701 二叉搜索树中的插入操作
3 LeetCode450 删除二叉树中的节点

今日任务:

  1. LeetCode235 二叉搜索树的最近公共祖先
  2. LeetCode701 二叉搜索树中的插入操作
  3. LeetCode450 删除二叉搜索树中的节点

资料来源:

  1. 代码随想录 | LeetCode235 二叉搜索树的最近公共祖先
  2. 代码随想录 | LeetCode701 二叉搜索树中的插入操作
  3. 代码随想录 | LeetCode450 删除二叉搜索树中的节点

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

题目

给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:“对于有根树 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 为不同节点且均存在于给定的二叉搜索树中。

这个思路和昨天大致相似,只是这次判断要快很多。如果这次递归的节点和p或者q值相等,那么就认为这个节点就是要找的节点;如果p比当前节点大同时q比当前节点小,那么这个节点也是要找的节点;如果p和q同时比当前节点大/小,就继续往右子树/左子树上找。

python
from typing import Optional # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if p.val > q.val: # 递归函数里p是较大的数字 return self.recursion(root, p, q) else: return self.recursion(root, q, p) def recursion(self, root: TreeNode, p: TreeNode, q: TreeNode) -> Optional[TreeNode]: if q.val < root.val < p.val or q.val == root.val or p.val == root.val: return root elif p.val < root.val and q.val < root.val and root.left is not None: return self.recursion(root.left, p, q) elif p.val > root.val and q.val > root.val and root.right is not None: return self.recursion(root.right, p, q)

2 LeetCode701 二叉搜索树中的插入操作

题目

给定二叉搜索树(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, 104]的范围内。
  • -108 <= Node.val <= 108
  • 所有值 Node.val 是 独一无二 的。
  • -108 <= val <= 108
  • 保证 val 在原始BST中不存在。

看到这个题的时候,有两个想法。一个想法是找到离要插入的节点最近的节点然后进行操作;另一个想法是以要插入的节点为根,重新构建一个树。

我写的代码是根据第一个想法而来的。先按中序找到第一个大于要插入节点的值的节点,之后在它的子树的最右侧插入节点。写完之后发现确实文档说得对,比想象的要简单。

python
# 我的代码 from collections import deque from typing import Optional # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if root is None: return TreeNode(val=val) stack = deque() node = root stack.append(root) while len(stack) != 0: node = stack.pop() if node is None: node = stack.pop() if node.val > val: if node.left is None: node.left = TreeNode(val=val) else: node = node.left while node.right is not None: node = node.right node.right = TreeNode(val=val) return root else: if node.right is not None: stack.append(node.right) stack.append(node) stack.append(None) if node.left is not None: stack.append(node.left) node = root while node.right is not None: node = node.right node.right = TreeNode(val=val) return root

看完文档之后发现我还是想复杂了。搜索二叉树无论插入什么值,这个值都一定能够在叶子节点上找到一个位置。那事情就好说了,按照要插入的数值一个劲往叶子节点找就行了,找到空就插入,然后直接返回根节点就行。

python
# 根据给定思路修改后的代码 from collections import deque from typing import Optional # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if root is None: return TreeNode(val) node = root pre_node = node while node is not None: pre_node = node if node.val > val: node = node.left else: node = node.right if pre_node.val > val: pre_node.left = TreeNode(val) else: pre_node.right = TreeNode(val) return root

3 LeetCode450 删除二叉树中的节点

题目

给定一个二叉搜索树的根节点 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, 104].
  • -105 <= Node.val <= 105
  • 节点值唯一
  • root 是合法的二叉搜索树
  • -105 <= key <= 105

进阶: 要求算法时间复杂度为 O(h),h 为树的高度。

第一思路是先找着这个节点和它的父节点,然后这个节点被它的右子树代替,它的左子树就成为右子树的最左边的节点的左子树。

python
# 我的代码 from typing import Optional # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: if root is None: return None pointer = root pre_pointer = None while pointer is not None: # 先找要删的节点和它的父节点 if pointer.val == key: break pre_pointer = pointer if pointer.val > key: pointer = pointer.left else: pointer = pointer.right if pointer is None: # 没找着 return root else: if pre_pointer is not None: # 如果要删的不是根节点 if pointer.right is not None: # 如果右子树不为空 if pre_pointer.left is pointer: # 接右子树 pre_pointer.left = pointer.right elif pre_pointer.right is pointer: pre_pointer.right = pointer.right # 从这开始接左子树 temp = pointer.right # 如果右子树不为空 就往右子树的左节点上找 找到空了再接上 while temp.left is not None: temp = temp.left temp.left = pointer.left else: # 如果右子树为空 那直接接左子树就好 if pre_pointer.left is pointer: # 接右子树 pre_pointer.left = pointer.left elif pre_pointer.right is pointer: pre_pointer.right = pointer.left return root else: # 如果要删的是根节点 root = root.right # 还是先接右子树 这次是将右子树作为根节点 if root is not None: # 上面一样的接法 temp = root while temp.left is not None: temp = temp.left temp.left = pointer.left return root else: # 如果右子树为空 那直接返回左子树就行了 return pointer.left

提示

代码随想录里提到了一个比较有趣的删节点的方法,虽然是针对普通二叉树的。

  1. 找到要删除的节点和要删除的节点的右子树的最左节点。
  2. 找到的这两个节点进行值的交换。
  3. 再将那个交换后的节点变成空。
cpp
class Solution { public: TreeNode* deleteNode(TreeNode* root, int key) { if (root == nullptr) return root; if (root->val == key) { if (root->right == nullptr) { // 这里第二次操作目标值:最终删除的作用 return root->left; } TreeNode *cur = root->right; while (cur->left) { cur = cur->left; } swap(root->val, cur->val); // 这里第一次操作目标值:交换目标值其右子树最左面节点。 } root->left = deleteNode(root->left, key); root->right = deleteNode(root->right, key); return root; } };

本文作者:御坂19327号

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!