Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root of the (modified) BST.
Three cases for deletion: (1) node has no children — just remove; (2) node has one child — replace with that child; (3) node has two children — replace with the inorder successor (smallest in right subtree) and delete successor.
- Search for the key recursively.
- If key < root.val: root.left = delete(root.left, key).
- If key > root.val: root.right = delete(root.right, key).
- If key == root.val: if no left child return right; if no right child return left; else find min in right subtree, set root.val = min.val, delete min from right subtree.
- Time Complexity: O(H) where H is height; O(log N) for balanced BST
- Space Complexity: O(H) recursion stack