Binary Search Tree | Set 3 (Iterative Delete)
Last Updated :
29 Jul, 2024
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:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int key;
Node* left;
Node* right;
Node(int k)
{
key = k;
left = right = NULL;
}
};
// Iterative Function to delete
// 'key' from the BST.
Node* delIterative(Node* root, int key)
{
Node* curr = root;
Node* prev = NULL;
// Check if the key is actually
// present in the BST.
// the variable prev points to
// the parent of the key to be deleted.
while (curr != NULL && curr->key != key) {
prev = curr;
if (key < curr->key)
curr = curr->left;
else
curr = curr->right;
}
// Key not present
if (curr == NULL)
return root;
// Check if the node to be
// deleted has atmost one child.
if (curr->left == NULL || curr->right == NULL) {
// newCurr will replace
// the node to be deleted.
Node* newCurr;
// if the left child does not exist.
if (curr->left == NULL)
newCurr = curr->right;
else
newCurr = curr->left;
// check if the node to
// be deleted is the root.
if (prev == NULL)
return newCurr;
// check if the node to be deleted
// is prev's left or right child
// and then replace this with newCurr
if (curr == prev->left)
prev->left = newCurr;
else
prev->right = newCurr;
// free memory of the
// node to be deleted.
delete curr;
}
// node to be deleted has
// two children.
else {
// Compute the inorder successor
Node* p = NULL;
Node* temp = curr->right;
while (temp->left != NULL) {
p = temp;
temp = temp->left;
}
// check if the parent of the inorder
// successor is the curr or not(i.e. curr=
// the node which has the same data as
// the given data by the user to be
// deleted). if it isn't, then make the
// the left child of its parent equal to
// the inorder successor'd right child.
if (p != NULL)
p->left = temp->right;
// if the inorder successor was the
// curr (i.e. curr = the node which has the
// same data as the given data by the
// user to be deleted), then make the
// right child of the node to be
// deleted equal to the right child of
// the inorder successor.
else
curr->right = temp->right;
curr->key = temp->key;
delete temp;
}
return root;
}
// Utility function to do inorder
// traversal
void inorder(Node* root)
{
if (root != NULL) {
inorder(root->left);
cout << root->key << " ";
inorder(root->right);
}
}
// Driver code
int main()
{
Node* root = new Node(10);
root->left = new Node(5);
root->right = new Node(15);
root->right->left = new Node(12);
root->right->right = new Node(18);
int x = 15;
root = delIterative(root, x);
inorder(root);
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int key;
struct Node* left;
struct Node* right;
};
struct Node* delIterative(struct Node* root, int key) {
struct Node* curr = root;
struct Node* prev = NULL;
// Check if the key is actually present in the BST.
// The variable prev points to the parent of the key
// to be deleted.
while (curr != NULL && curr->key != key) {
prev = curr;
if (key < curr->key)
curr = curr->left;
else
curr = curr->right;
}
// Key not present
if (curr == NULL)
return root;
// Check if the node to be deleted has at most
// one child.
if (curr->left == NULL || curr->right == NULL) {
struct Node* newCurr;
// If the left child does not exist.
if (curr->left == NULL)
newCurr = curr->right;
else
newCurr = curr->left;
// Check if the node to be deleted is the root.
if (prev == NULL)
return newCurr;
// Check if the node to be deleted is prev's left or
// right child and then replace this with newCurr
if (curr == prev->left)
prev->left = newCurr;
else
prev->right = newCurr;
// Free memory of the node to be deleted.
free(curr);
} else {
// Node to be deleted has two children.
struct Node* p = NULL;
struct Node* temp = curr->right;
while (temp->left != NULL) {
p = temp;
temp = temp->left;
}
if (p != NULL)
p->left = temp->right;
else
curr->right = temp->right;
curr->key = temp->key;
free(temp);
}
return root;
}
void inorder(struct Node* root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->key);
inorder(root->right);
}
}
struct Node* createNode(int key) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->key = key;
newNode->left = newNode->right = NULL;
return newNode;
}
// Driver code
int main() {
struct Node* root = createNode(10);
root->left = createNode(5);
root->right = createNode(15);
root->right->left = createNode(12);
root->right->right = createNode(18);
int x = 15;
root = delIterative(root, x);
inorder(root);
return 0;
}
Java
class Node {
int key;
Node left, right;
Node(int key) {
this.key = key;
this.left = this.right = null;
}
}
class GfG {
public static Node delIterative(Node root, int key) {
Node curr = root;
Node prev = null;
// Check if the key is actually present in the BST.
// The variable prev points to the parent of the key
// to be deleted.
while (curr != null && curr.key != key) {
prev = curr;
if (key < curr.key)
curr = curr.left;
else
curr = curr.right;
}
// Key not present
if (curr == null)
return root;
// Check if the node to be deleted has at most one child.
if (curr.left == null || curr.right == null) {
Node newCurr;
// If the left child does not exist.
if (curr.left == null)
newCurr = curr.right;
else
newCurr = curr.left;
// Check if the node to be deleted is the root.
if (prev == null)
return newCurr;
// Check if the node to be deleted is prev's left or
// right child and then replace this with newCurr.
if (curr == prev.left)
prev.left = newCurr;
else
prev.right = newCurr;
} else {
// Node to be deleted has two children.
Node p = null;
Node temp = curr.right;
while (temp.left != null) {
p = temp;
temp = temp.left;
}
if (p != null)
p.left = temp.right;
else
curr.right = temp.right;
curr.key = temp.key;
}
return root;
}
// Utility function to do inorder traversal
public static void inorder(Node root) {
if (root != null) {
inorder(root.left);
System.out.print(root.key + " ");
inorder(root.right);
}
}
// Driver code
public static void main(String[] args) {
Node root = new Node(10);
root.left = new Node(5);
root.right = new Node(15);
root.right.left = new Node(12);
root.right.right = new Node(18);
int x = 15;
root = delIterative(root, x);
inorder(root);
}
}
Python
class Node:
def __init__(self, key):
self.key = key
self.left = self.right = None
# Iterative approach to
# delete 'key' from the BST.
def del_iterative(root, key):
curr = root
prev = None
# First check if the key is
# actually present in the BST.
# the variable prev points to the
# parent of the key to be deleted
while (curr != None and curr.key != key):
prev = curr
if curr.key < key:
curr = curr.right
else:
curr = curr.left
if curr == None:
return root
# Check if the node to be
# deleted has atmost one child
if curr.left == None or\
curr.right == None:
# newCurr will replace
# the node to be deleted.
newCurr = None
# if the left child does not exist.
if curr.left == None:
newCurr = curr.right
else:
newCurr = curr.left
# check if the node to
# be deleted is the root.
if prev == None:
return newCurr
# Check if the node to be
# deleted is prev's left or
# right child and then
# replace this with newCurr
if curr == prev.left:
prev.left = newCurr
else:
prev.right = newCurr
curr = None
# node to be deleted
# has two children.
else:
p = None
temp = None
# Compute the inorder
# successor of curr.
temp = curr.right
while(temp.left != None):
p = temp
temp = temp.left
# check if the parent of the
# inorder successor is the root or not.
# if it isn't, then make the left
# child of its parent equal to the
# inorder successor's right child.
if p != None:
p.left = temp.right
else:
# if the inorder successor was
# the root, then make the right child
# of the node to be deleted equal
# to the right child of the inorder
# successor.
curr.right = temp.right
curr.data = temp.key
return root
def inorder(root):
if root is not None:
inorder(root.left)
print(root.key, end=" ")
inorder(root.right)
# Driver code
if __name__ == "__main__":
root = Node(10)
root.left = Node(5)
root.right = Node(15)
root.right.left = Node(12)
root.right.right = Node(18)
x = 15
root = del_iterative(root, x)
inorder(root)
C#
class Node {
public int key;
public Node left, right;
public Node(int key) {
this.key = key;
this.left = this.right = null;
}
}
class GfG {
public static Node DelIterative(Node root, int key) {
Node curr = root;
Node prev = null;
// Check if the key is actually present in the BST.
// The variable prev points to the parent of the key
// to be deleted.
while (curr != null && curr.key != key) {
prev = curr;
if (key < curr.key)
curr = curr.left;
else
curr = curr.right;
}
// Key not present
if (curr == null)
return root;
// Check if the node to be deleted has at
// most one child.
if (curr.left == null || curr.right == null) {
Node newCurr;
// If the left child does not exist.
if (curr.left == null)
newCurr = curr.right;
else
newCurr = curr.left;
// Check if the node to be deleted is the root.
if (prev == null)
return newCurr;
// Check if the node to be deleted is prev's left or
// right child and then replace this with newCurr.
if (curr == prev.left)
prev.left = newCurr;
else
prev.right = newCurr;
} else {
// Node to be deleted has two children.
Node p = null;
Node temp = curr.right;
while (temp.left != null) {
p = temp;
temp = temp.left;
}
if (p != null)
p.left = temp.right;
else
curr.right = temp.right;
curr.key = temp.key;
}
return root;
}
// Utility function to do inorder traversal
public static void Inorder(Node root) {
if (root != null) {
Inorder(root.left);
System.Console.Write(root.key + " ");
Inorder(root.right);
}
}
// Driver code
public static void Main(string[] args) {
Node root = new Node(10);
root.left = new Node(5);
root.right = new Node(15);
root.right.left = new Node(12);
root.right.right = new Node(18);
int x = 15;
root = DelIterative(root, x);
Inorder(root);
}
}
JavaScript
class Node {
constructor(key) {
this.key = key;
this.left = this.right = null;
}
}
function delIterative(root, key) {
let curr = root;
let prev = null;
// Check if the key is actually present in the BST.
// The variable prev points to the parent of the key
// to be deleted.
while (curr !== null && curr.key !== key) {
prev = curr;
if (key < curr.key) {
curr = curr.left;
} else {
curr = curr.right;
}
}
// Key not present
if (curr === null) {
return root;
}
// Check if the node to be deleted has at most one child.
if (curr.left === null || curr.right === null) {
let newCurr = (curr.left === null) ? curr.right : curr.left;
// Check if the node to be deleted is the root.
if (prev === null) {
return newCurr;
}
// Check if the node to be deleted is prev's left or
// right child and then replace this with newCurr.
if (curr === prev.left) {
prev.left = newCurr;
} else {
prev.right = newCurr;
}
} else {
// Node to be deleted has two children.
let p = null;
let temp = curr.right;
while (temp.left !== null) {
p = temp;
temp = temp.left;
}
if (p !== null) {
p.left = temp.right;
} else {
curr.right = temp.right;
}
curr.key = temp.key;
}
return root;
}
function inorder(root) {
if (root !== null) {
inorder(root.left);
process.stdout.write(root.key + " ");
inorder(root.right);
}
}
// Driver code
const root = new Node(10);
root.left = new Node(5);
root.right = new Node(15);
root.right.left = new Node(12);
root.right.right = new Node(18);
const x = 15;
const newRoot = delIterative(root, x);
inorder(newRoot);
Time Complexity : O(h) where h is height of the BST
Auxiliary Space: O(1)
Similar Reads
Implement Binary Search Tree(BST) Iterator Binary Search Trees (BSTs) are data structures, in computer science. They are commonly used for searching, insertion and deletion operations. In situations it becomes necessary to traverse a BST in an order. For example an in order traversal visits nodes in ascending order based on their values. Thi
6 min read
Iterative Search for a key 'x' in Binary Tree Given a Binary Tree and a key to be searched in it, write an iterative method that returns true if key is present in Binary Tree, else false. For example, in the following tree, if the searched key is 3, then function should return true and if the searched key is 12, then function should return fals
14 min read
Delete the last leaf node in a Binary Tree Given a Binary Tree, the task is to find and DELETE the last leaf node.The leaf node is a node with no children. The last leaf node would be the node that is traversed last in sequence during Level Order Traversal. The problem statement is to identify this last visited node and delete this particula
15+ min read
Threaded Binary Search Tree | Deletion A threaded binary tree node looks like following. C++ struct Node { struct Node *left, *right; int info; // false if left pointer points to predecessor // in Inorder Traversal bool lthread; // false if right pointer points to predecessor // in Inorder Traversal bool rthread; }; Java static class Nod
15+ min read
Deletion in Binary Search Tree (BST) Given a BST, the task is to delete a node in this BST, which can be broken down into 3 scenarios:Case 1. Delete a Leaf Node in BST Case 2. Delete a Node with Single Child in BSTDeleting a single child node is also simple in BST. Copy the child to the node and delete the node. Case 3. Delete a Node w
10 min read