1. Deleting from an Empty Tree
If the binary search tree is empty (i.e., the root is null
), there's nothing to delete. We simply return the tree as is — which is still empty. This is a base case and helps terminate recursion safely.
2. Deleting a Leaf Node (Node with No Children)
Suppose the node to be deleted is a leaf, meaning it has no left or right children. In this case, we can safely remove the node by setting its parent's pointer to null
. For example, deleting 3 from a tree where 3 has no children results in simply detaching it from its parent.
3. Deleting a Node with One Child
If the node to be deleted has only one child, the simplest approach is to bypass the node and connect its parent directly to its only child. This ensures the BST structure remains intact. For instance, deleting a node like 7 that only has a right child (8) would mean linking 7’s parent directly to 8.
4. Deleting a Node with Two Children
This is the most complex case. If a node has both left and right children, we must maintain the BST properties. The standard solution is to replace the value of the node with its in-order successor (the smallest value in the right subtree), and then recursively delete the successor node. This ensures that all left values remain smaller and right values remain larger, preserving the BST structure.
5. Key Not Found in the Tree
During traversal, if we reach a null
node and haven't found the key, it means the key does not exist in the tree. In this case, the original tree remains unchanged. We simply return the node back up the recursive stack.
In all cases, it's important to preserve the structure and rules of a binary search tree while performing the deletion operation.