Given a BST, write an efficient function to delete a given key in it.

Practice this problem

There are three possible cases to consider deleting a node from BST:

 
Case 1: Deleting a node with no children: remove the node from the tree.

Deletion from BST – Case 1

Case 2: Deleting a node with two children: call the node to be deleted N. Do not delete N. Instead, choose either its inorder successor node or its inorder predecessor node, R. Copy the value of R to N, then recursively call delete on R until reaching one of the first two cases. If we choose the inorder successor of a node, as the right subtree is not NULL (our present case is a node with 2 children), then its inorder successor is a node with the least value in its right subtree, which will have at a maximum of 1 subtree, so deleting it would fall in one of the first 2 cases.

Deletion from BST – Case 2

Case 3: Deleting a node with one child: remove the node and replace it with its child.

Deletion from BST – Case 3

Broadly speaking, nodes with children are harder to delete. As with all binary trees, a node’s inorder successor is its right subtree’s leftmost child, and a node’s inorder predecessor is the left subtree’s rightmost child. In either case, this node will have zero or one child. Delete it according to one of the two simpler cases above.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

8 10 12 15 20

Java


Download  Run Code

Output:

8 10 12 15 20

Python


Download  Run Code

Output:

8 10 12 15 20

The time complexity of the above solution is O(n), where n is the size of the BST. The auxiliary space required by the program is O(n) for recursion (call stack).

 
The above solution initially searches the key in the BST and also find its parent pointer. We can easily modify the code to recursively search the key in the deletion procedure itself and let recursion take care of updating the parent pointer.

C++


Download  Run Code

Output:

8 10 15 20 25

Java


Download  Run Code

Output:

8 10 15 20 25

Python


Download  Run Code

Output:

8 10 15 20 25

The time complexity of the above solution is O(n), where n is the size of the BST, and requires space proportional to the tree’s height for the call stack.

 
Also See:

Insertion in a BST – Iterative and Recursive Solution

Search a given key in BST – Iterative and Recursive Solution

 
References: https://en.wikipedia.org/wiki/Binary_search_tree