LeetCode 450. Delete Node in a BST

题目

Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.

Basically, the deletion can be divided into two stages:

  1. Search for a node to remove.
  2. If the node is found, delete the node.

Follow up: Can you solve it with time complexity O(height of tree)?

Example 1:

1
2
3
4
5
Input: root = [5,3,6,2,4,null,7], key = 3
Output: [5,4,6,2,null,null,7]
Explanation: Given key to delete is 3. So we find the node with value 3 and delete it.
One valid answer is [5,4,6,2,null,null,7], shown in the above BST.
Please notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted.

Example 2:

1
2
3
Input: root = [5,3,6,2,4,null,7], key = 0
Output: [5,3,6,2,4,null,7]
Explanation: The tree does not contain a node with value = 0.

Example 3:

1
2
Input: root = [], key = 0
Output: []

Constraints:

  • The number of nodes in the tree is in the range [0, 10^4].
  • -10^5 <= Node.val <= 10^5
  • Each node has a unique value.
  • root is a valid binary search tree.
  • -10^5 <= key <= 10^5

思路

  1. 被删除节点没有左子树:返回其右子树
  2. 被删除节点节点没有右子树:返回其左子树
  3. 被删除节点既有左子树,又有右子树:
    1)查找到其右子树的最小值的节点,替换掉被删除的节点,并删除找到的最小节点
    2)查找到其左子树的最大值的节点,替换掉被删除的节点,并删除找到的最大节点

下面的做法是查找右子树的最小值节点的方法,最小节点就是右子树中的最靠左边的节点。代码使用的递归,最核心的是找到该节点之后的操作,特别是把值进行交换一步很重要,因为我们并没有删除了该最小值节点,所以把最小值的节点赋值成要查找的节点,然后在之后的操作中将会把它删除。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 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: TreeNode, key: int) -> TreeNode:
if not root: return None
if root.val == key:
if not root.right:
left = root.left
return left
else:
right = root.right
while right.left:
right = right.left
root.val, right.val = right.val, root.val
root.left = self.deleteNode(root.left, key)
root.right = self.deleteNode(root.right, key)
return root