Problem Description
Given the root node of a Binary Search Tree (BST) and a key, delete the node with the given key and return the (possibly updated) root of the BST. The deletion is performed in two stages: first, search for the node; second, delete it while maintaining the BST properties.
Key Insights
- If the key is not found in the BST, return the original tree.
- There are three deletion cases:
- The node is a leaf (no children).
- The node has one child (left or right).
- The node has two children.
- For a node with two children, find the inorder successor (smallest node in the right subtree) or the inorder predecessor (largest node in the left subtree) to replace the node's value.
- Recursively adjust the tree to preserve the BST invariants.
Space and Time Complexity
Time Complexity: O(h), where h is the height of the tree (in the worst-case O(n) for a skewed tree).
Space Complexity: O(h), due to the recursion stack.
Solution
We use a recursive approach to traverse the tree to find the node with the given key. When the node is found:
- If it has zero or one child, return the non-null child or null.
- If it has two children, find the inorder successor (the smallest node in the right subtree), copy its value to the current node, and then delete the successor recursively. This ensures that the BST property is maintained after deletion.