Deletion in Binary Search Tree (BST)
Last Updated :
23 Jul, 2025
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 BST
Deleting a single child node is also simple in BST. Copy the child to the node and delete the node.
Case 3. Delete a Node with Both Children in BST
Deleting a node with both children is not so simple. Here we have to delete the node is such a way, that the resulting tree follows the properties of a BST.
The trick is to find the inorder successor of the node. Copy contents of the inorder successor to the node, and delete the inorder successor.
Note: Inorder predecessor can also be used.
Note: Inorder successor is needed only when the right child is not empty. In this particular case, the inorder successor can be obtained by finding the minimum value in the right child of the node.
Recursive Implementation of Deletion operation in a BST:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int key;
Node* left;
Node* right;
Node(int k){
key = k;
left = right = nullptr;
}
};
// Note that it is not a generic inorder
// successor function. It mainly works
// when right child is not empty which is
// the case wwe need in BST delete
Node* getSuccessor(Node* curr){
curr = curr->right;
while (curr != nullptr && curr->left != nullptr)
curr = curr->left;
return curr;
}
// This function deletes a given key x from
// the give BST and returns modified root of
// the BST (if it is modified)
Node* delNode(Node* root, int x){
// Base case
if (root == nullptr)
return root;
// If key to be searched is in a subtree
if (root->key > x)
root->left = delNode(root->left, x);
else if (root->key < x)
root->right = delNode(root->right, x);
// If root matches with the given key
else {
// Cases when root has 0 children
// or only right child
if (root->left == nullptr) {
Node* temp = root->right;
delete root;
return temp;
}
// When root has only left child
if (root->right == nullptr) {
Node* temp = root->left;
delete root;
return temp;
}
// When both children are present
Node* succ = getSuccessor(root);
root->key = succ->key;
root->right = delNode(root->right, succ->key);
}
return root;
}
// Utility function to do inorder
// traversal
void inorder(Node* root){
if (root != nullptr) {
inorder(root->left);
cout << root->key << " ";
inorder(root->right);
}
}
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 = delNode(root, x);
inorder(root);
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int key;
struct Node* left;
struct Node* right;
};
// Note that it is not a generic inorder successor
// function. It mainly works when the right child
// is not empty, which is the case we need in
// BST delete.
struct Node* getSuccessor(struct Node* curr) {
curr = curr->right;
while (curr != NULL && curr->left != NULL)
curr = curr->left;
return curr;
}
// This function deletes a given key x from the
// given BST and returns the modified root of
// the BST (if it is modified)
struct Node* delNode(struct Node* root, int x) {
// Base case
if (root == NULL)
return root;
// If key to be searched is in a subtree
if (root->key > x)
root->left = delNode(root->left, x);
else if (root->key < x)
root->right = delNode(root->right, x);
else {
// If root matches with the given key
// Cases when root has 0 children or
// only right child
if (root->left == NULL) {
struct Node* temp = root->right;
free(root);
return temp;
}
// When root has only left child
if (root->right == NULL) {
struct Node* temp = root->left;
free(root);
return temp;
}
// When both children are present
struct Node* succ = getSuccessor(root);
root->key = succ->key;
root->right = delNode(root->right, succ->key);
}
return root;
}
struct Node* createNode(int key) {
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
newNode->key = key;
newNode->left = newNode->right = NULL;
return newNode;
}
// Utility function to do inorder traversal
void inorder(struct Node* root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->key);
inorder(root->right);
}
}
// 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 = delNode(root, x);
inorder(root);
return 0;
}
Java
class Node {
int key;
Node left, right;
public Node(int item) {
key = item;
left = right = null;
}
}
class GfG {
// This function deletes a given key x from the
// given BST and returns the modified root of
// the BST (if it is modified).
static Node delNode(Node root, int x) {
// Base case
if (root == null) {
return root;
}
// If key to be searched is in a subtree
if (root.key > x) {
root.left = delNode(root.left, x);
} else if (root.key < x) {
root.right = delNode(root.right, x);
} else {
// If root matches with the given key
// Cases when root has 0 children or
// only right child
if (root.left == null) {
return root.right;
}
// When root has only left child
if (root.right == null) {
return root.left;
}
// When both children are present
Node succ = getSuccessor(root);
root.key = succ.key;
root.right = delNode(root.right, succ.key);
}
return root;
}
// Note that it is not a generic inorder successor
// function. It mainly works when the right child
// is not empty, which is the case we need in BST
// delete.
static Node getSuccessor(Node curr) {
curr = curr.right;
while (curr != null && curr.left != null) {
curr = curr.left;
}
return curr;
}
// Utility function to do inorder traversal
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 = delNode(root, x);
inorder(root);
}
}
Python
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# Note that it is not a generic inorder successor
# function. It mainly works when the right child
# is not empty, which is the case we need in BST
# delete.
def get_successor(curr):
curr = curr.right
while curr is not None and curr.left is not None:
curr = curr.left
return curr
# This function deletes a given key x from the
# given BST and returns the modified root of the
# BST (if it is modified).
def del_node(root, x):
# Base case
if root is None:
return root
# If key to be searched is in a subtree
if root.key > x:
root.left = del_node(root.left, x)
elif root.key < x:
root.right = del_node(root.right, x)
else:
# If root matches with the given key
# Cases when root has 0 children or
# only right child
if root.left is None:
return root.right
# When root has only left child
if root.right is None:
return root.left
# When both children are present
succ = get_successor(root)
root.key = succ.key
root.right = del_node(root.right, succ.key)
return root
# Utility function to do inorder traversal
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_node(root, x)
inorder(root)
print()
C#
using System;
class Node {
public int key;
public Node left, right;
public Node(int item) {
key = item;
left = right = null;
}
}
class GfG {
// This function deletes a given key x from the
// given BST and returns the modified root of
// the BST (if it is modified).
public static Node DelNode(Node root, int x) {
// Base case
if (root == null) {
return root;
}
// If key to be searched is in a subtree
if (root.key > x) {
root.left = DelNode(root.left, x);
} else if (root.key < x) {
root.right = DelNode(root.right, x);
} else {
// If root matches with the given key
// Cases when root has 0 children or
// only right child
if (root.left == null) {
return root.right;
}
// When root has only left child
if (root.right == null) {
return root.left;
}
// When both children are present
Node succ = GetSuccessor(root);
root.key = succ.key;
root.right = DelNode(root.right, succ.key);
}
return root;
}
// Note that it is not a generic inorder successor
// function. It mainly works when the right child
// is not empty, which is the case we need in BST
// delete.
public static Node GetSuccessor(Node curr) {
curr = curr.right;
while (curr != null && curr.left != null) {
curr = curr.left;
}
return curr;
}
// Utility function to do inorder traversal
public static void Inorder(Node root) {
if (root != null) {
Inorder(root.left);
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 = DelNode(root, x);
Inorder(root);
}
}
JavaScript
class Node {
constructor(key) {
this.key = key;
this.left = null;
this.right = null;
}
}
// Note that it is not a generic inorder successor
// function. It mainly works when the right child
// is not empty, which is the case we need in BST
// delete.
function getSuccessor(curr) {
curr = curr.right;
while (curr !== null && curr.left !== null) {
curr = curr.left;
}
return curr;
}
// This function deletes a given key x from the
// given BST and returns the modified root of the
// BST (if it is modified).
function delNode(root, x) {
// Base case
if (root === null) {
return root;
}
// If key to be searched is in a subtree
if (root.key > x) {
root.left = delNode(root.left, x);
} else if (root.key < x) {
root.right = delNode(root.right, x);
} else {
// If root matches with the given key
// Cases when root has 0 children or
// only right child
if (root.left === null)
return root.right;
// When root has only left child
if (root.right === null)
return root.left;
// When both children are present
let succ = getSuccessor(root);
root.key = succ.key;
root.right = delNode(root.right, succ.key);
}
return root;
}
// Utility function to do inorder traversal
function inorder(root) {
if (root !== null) {
inorder(root.left);
console.log(root.key + " ");
inorder(root.right);
}
}
// Driver code
let 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);
let x = 15;
root = delNode(root, x);
inorder(root);
console.log();
Time Complexity: O(h), where h is the height of the BST.
Auxiliary Space: O(h).
The above recursive solution does two traversals across height when both the children are not NULL. We can optimize the solution for this particular case. Please refer Optimized Recursive Delete in BST for details.
We can avoid extra O(h) space and recursion call overhead with iterative solution. The iterative solution has same time complexity but works more efficiently.
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