LeetCode刷题实战450:删除二叉搜索树中的节点
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:
Search for a node to remove.
If the node is found, delete the node.
示例
解题
class Solution:
def deleteNode(self, root: TreeNode, key: int) -> TreeNode:
if not root:
return None
def successor(root): # 代表中序遍历序列的下一个节点,即比当前节点大的最小节点
root = root.right
while root.left:
root = root.left
return root.val
def predecessor(root):
root = root.left
while root.right:
root = root.right
return root.val
if key > root.val: # 如果key大于根节点,则从右子树寻找
root.right = self.deleteNode(root.right, key)
elif key < root.val: # 如果key小于根节点,则从左子树寻找
root.left = self.deleteNode(root.left, key)
else: # key == 根节点
if not root.left and not root.right: # 如果根节点是叶节点,则直接删除该节点
return None
if root.right: # 如果该节点有右节点,则要找比它大的下一个节点(后继节点)
root.val = successor(root) # 用它的后继节点代替它
root.right = self.deleteNode(root.right, root.val)
else:
root.val = predecessor(root)
root.left = self.deleteNode(root.left, root.val)
return root
LeetCode刷题实战446:等差数列划分 II - 子序列