给定一个二叉搜索树的根节点 root 和一个值 key,删除二叉搜索树中的 key 对应的节点,并保证二叉搜索树的性质不变。返回二叉搜索树(有可能被更新)的根节点的引用。
一般来说,删除节点可分为两个步骤:
首先找到需要删除的节点;
如果找到了,删除它。
说明: 要求算法时间复杂度为 O(h),h 为树的高度。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/delete-node-in-a-bst
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution: def successor(self, root): """ One step right and then always left """ root = root.right#要是该赋值的右节点存在左节点,那么优先考虑左节点 while root.left: root = root.left return root.val def predecessor(self, root): """ One step left and then always right """ root = root.left while root.right: root = root.right return root.val def deleteNode(self, root: TreeNode, key: int) -> TreeNode: if not root: return None # delete from the right subtree if key > root.val:#那么就在右子树找 root.right = self.deleteNode(root.right, key) # delete from the left subtree elif key < root.val:#那么久在左子树找 root.left = self.deleteNode(root.left, key) # delete the current node else: # the node is a leaf if not (root.left or root.right):#没有节点 root = None # the node is not a leaf and has a right child elif root.right:#如果存在右节点,那么就把右节点的值赋给它 root.val = self.successor(root) root.right = self.deleteNode(root.right, root.val) # the node is not a leaf, has no right child, and has a left child else: root.val = self.predecessor(root) root.left = self.deleteNode(root.left, root.val) return root