链接:https://leetcode.cn/problems/delete-node-in-a-bst/
二叉搜索树的增删改查都是必会的内容,但是删除相对于其他操作较难一点,可以通过这道题来进行练习。
题目描述
给定一个二叉搜索树的根节点 root 和一个值 key,删除二叉搜索树中的 key 对应的节点,并保证二叉搜索树的性质不变。返回二叉搜索树(有可能被更新)的根节点的引用。
递归解法
class Solution:
"""
递归解法
"""
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
"""
删除根为root的BST中node.val等于key的节点,返回删除后的根节点(根节点可能变化)
"""
if not root:
return None
if key < root.val:
root.left = self.deleteNode(root.left, key)
elif root.val < key:
root.right = self.deleteNode(root.right, key)
# # root可能有0或1个孩子节点,但是处理方式相同,返回孩子节点
elif not root.left or not root.right:
child = root.left if root.left else root.right
return child
else:
successor = root.right # 使用后继节点代替root
while successor.left:
successor = successor.left
root.val = successor.val # root.val赋值为后继节点值
root.right = self.deleteNode(root.right, successor.val)
return root
迭代解法
迭代解法基本思路与上相同,就是要多分类讨论删除的节点是不是根节点。
class Solution:
"""
非递归解法
"""
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
if not root:
return root
node, father = self.findNode(root, key)
if not node:
return root
return self.delete(root, father, node)
def delete(self, root, father, node):
if node.left and node.right:
suc_father, successor = self.findSuccessor(node)
node.val = successor.val
return self.delete(root, suc_father, successor)
if not node.left and not node.right:
if root == node:
return None
if father.left == node:
father.left = None
else:
father.right = None
return root
child = node.left if node.left else node.right
if root == node:
return child
if father.left == node:
father.left = child
else:
father.right = child
return root
def findNode(self, root, key):
if not root:
return root
if root.val == key:
return root, None
father = root
while root:
if root.val == key:
return root, father
elif key < root.val:
father = root
root = root.left
else:
father = root
root = root.right
return None, None
def findSuccessor(self, root):
successor = root.right
father = root
while successor.left:
father = successor
successor = successor.left
return father, successor