Understanding the Problem
We are given a Binary Search Tree (BST) and a key. Our goal is to delete the node with the given key from the BST while maintaining the properties of a BST:
- All values in the left subtree are less than the node’s value.
- All values in the right subtree are greater than the node’s value.
This problem helps us understand recursive tree operations and handling multiple cases based on the structure of the tree.
Step-by-Step Solution with Example
Step 1: Understand the Input Example
Consider the following BST:
5
/ 3 6
/ 2 4 7
Let’s say we want to delete the node with value 3
. Node 3 has two children: 2 and 4.
Step 2: Traverse the Tree to Locate the Node
We start from the root (5). Since 3 is less than 5, we go to the left child. Now we are at 3, which matches the key. So this is the node we want to delete.
Step 3: Handle the Case - Node Has Two Children
Node 3 has both left and right children. In such cases, we:
- Find the in-order successor (smallest value in the right subtree). Here, that’s
4
.
- Replace the value of node 3 with 4.
- Now we recursively delete the node with value 4 in the right subtree.
This keeps the BST structure valid.
Step 4: Recursively Delete the In-Order Successor
Now we move to the right subtree of node 3 (which now has value 4). We find node 4, which is a leaf (no children), so we delete it by returning null
.
Step 5: Final Tree After Deletion
The updated BST looks like this:
5
/ 4 6
/ 2 7
Node 3 has been replaced by 4, and the original 4 node is removed.
Edge Cases
Edge Case 1: Deleting from an Empty Tree
If the root is null
, the tree is empty. There's nothing to delete, so we return null
.
Edge Case 2: Node Not Found
If we reach a null
node during traversal and haven’t found the key, it means the key doesn’t exist. We simply return the current node.
Edge Case 3: Node is a Leaf
If the node to delete has no children, we can directly remove it by returning null
.
Edge Case 4: Node with One Child
If the node has only one child, we return that child and skip the current node, effectively deleting it.
Finally
Deleting a node from a BST involves careful consideration of three scenarios: deleting a leaf, deleting a node with one child, and deleting a node with two children. Using recursion helps elegantly handle each case. Understanding in-order successor and BST structure rules is key to solving this problem correctly and efficiently.
Comments
Loading comments...