![]() |
VOOZH | about |
Given a binary search tree and a node of the binary search tree, the task is to delete the node from the Binary Search tree Iteratively.
Here are the three cases that arise while performing a delete operation on a BST: We have already discussed recursive solution to delete a key in BST. Here we are going to discuss an iterative approach which is faster, requires O(1) auxiliary space.
1. Case 1: Node to be deleted is a leaf node. Directly delete the node from the tree.
10 10
/ \ delete(5) / \
7 15 ---------> 7 15
/ \ / \ \ / \
5 8 11 18 8 11 18
2. Case 2: Node to be deleted is an internal node with two children. Copy the contents of the inorder successor of the node to be deleted and delete the inorder successor. The inorder successor can be found by finding the minimum element in the right subtree of the node.
inorderSuccessor(10) = 11.
10 11
/ \ delete(10) / \
7 15 ---------> 7 15
/ \ / \ / \ \
5 8 11 18 5 8 18
3. Case 3: Node to be deleted is an internal node with one child. For this case, delete the node and move its child up to take its place.
10 10
/ \ delete(15) / \
7 15 ---------> 7 11
/ \ / / \
5 8 11 5 8
The intuition behind deleting the inorder successor in Case 2 is that the inorder successor of a node with two children will always be greater than all elements in the left sub-tree of the node since it is the smallest node in the right sub-tree of the node and the inorder successor of the node will always be smaller than all other nodes in the right sub-tree of the node.
This preserves the BST property of all nodes in the left sub-tree of a given node are smaller than the given node and all nodes in the right sub-tree of the given node are greater than the given node.
Below is the implementation of the above approach:
5 10 12 18
Time Complexity : O(h) where h is height of the BST
Auxiliary Space: O(1)