Deleting a node in a BST means removing the target node while ensuring that the tree remains a valid BST. Depending on the structure of the node to be deleted, there are three possible scenarios:
Case 1: Node has No Children (Leaf Node)
If the target node is a leaf node, it can be directly removed from the tree since it has no child to maintain.
If the target node has only one child, we remove the node and connect its parent directly to its only child. This way, the tree remains valid after deletion of target node.
Working:
Case 3: Node has Two Children
If the target node has two children, deletion is slightly more complex.
To maintain the BST property, we need to find a replacement node for the target. The replacement can be either:
The inorder successor — the smallest value in the right subtree, which is the next greater value than the target node.
The inorder predecessor — the largest value in the left subtree, which is the next smaller value than the target node.
Once the replacement node is chosen, we replace the target node’s value with that node’s value, and then delete the replacement node, which will now fall under Case 1 (no children) or Case 2 (one child).
Note: Inorder predecessor can also be used.
Working:
The deletion process in BST depends on the number of children of the node.
No children means simply remove the node.
One child means remove the node and connect its parent to the node’s only child.
Two children means replace the node with its inorder successor/predecessor and delete that node.
This ensures that the BST property remains intact after every deletion.
Output
10
5 18
N N 12 N
Time Complexity: O(h), where h is the height of the BST. Auxiliary Space: O(h).