Binary Search Tree | Set 3 (Iterative Delete)
Last Updated :
15 Jul, 2025
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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem