SDE & MLE Prep

450. Delete Node in a BST

Problem

Delete the node with value key from a BST, if it exists, and return the root of a valid BST. Any valid result is accepted.

Example: [5,3,6,2,4,null,7], key = 3 → [5,4,6,2,null,null,7]

Constraints: follow-up: O(height) time.

Find the node. 0 or 1 child → replace it with that child. 2 children → copy the in-order successor (min of the right subtree) into it, then delete the successor from the right subtree.

Complexity: O(h).

class Solution:
    def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
        if not root:
            return None
        if key < root.val:
            root.left = self.deleteNode(root.left, key)
        elif key > root.val:
            root.right = self.deleteNode(root.right, key)
        else:
            if not root.left or not root.right:
                return root.left or root.right
            succ = root.right
            while succ.left:
                succ = succ.left
            root.val = succ.val
            root.right = self.deleteNode(root.right, succ.val)
        return root