Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice on BST
  • MCQs on BST
  • BST Tutorial
  • BST Insertion
  • BST Traversals
  • BST Searching
  • BST Deletion
  • Check BST
  • Balance a BST
  • Self-Balancing BST
  • AVL Tree
  • Red-Black Tree
  • Splay Tree
  • BST Application
  • BST Advantage
Open In App
Next Article:
Binary Search Tree (BST) Traversals – Inorder, Preorder, Post Order
Next article icon

Deletion in Binary Search Tree (BST)

Last Updated : 05 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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

d1

Deletion 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. 

file

Deletion in BST

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.

d3

Deletion in Binary Tree


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(); 

Output
5 10 12 18 

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.

Iterative Implementation of Deletion operation in a BST:



Next Article
Binary Search Tree (BST) Traversals – Inorder, Preorder, Post Order
author
kartik
Improve
Article Tags :
  • Binary Search Tree
  • DSA
  • Accolite
  • Amazon
  • Qualcomm
  • Samsung
Practice Tags :
  • Accolite
  • Amazon
  • Qualcomm
  • Samsung
  • Binary Search Tree

Similar Reads

  • Binary Search Tree
    A Binary Search Tree (or BST) is a data structure used in computer science for organizing and storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right chi
    3 min read
  • Introduction to Binary Search Tree
    Binary Search Tree is a data structure used in computer science for organizing and storing data in a sorted manner. Binary search tree follows all properties of binary tree and for every nodes, its left subtree contains values less than the node and the right subtree contains values greater than the
    3 min read
  • Applications of BST
    Binary Search Tree (BST) is a data structure that is commonly used to implement efficient searching, insertion, and deletion operations along with maintaining sorted sequence of data. Please remember the following properties of BSTs before moving forward. The left subtree of a node contains only nod
    2 min read
  • Applications, Advantages and Disadvantages of Binary Search Tree
    A Binary Search Tree (BST) is a data structure used to storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right child containing values greater than the p
    2 min read
  • Insertion in Binary Search Tree (BST)
    Given a BST, the task is to insert a new node in this BST. Example: How to Insert a value in a Binary Search Tree:A new key is always inserted at the leaf by maintaining the property of the binary search tree. We start searching for a key from the root until we hit a leaf node. Once a leaf node is f
    15+ min read
  • Searching in Binary Search Tree (BST)
    Given a BST, the task is to search a node in this BST. For searching a value in BST, consider it as a sorted array. Now we can easily perform search operation in BST using Binary Search Algorithm. Input: Root of the below BST Output: TrueExplanation: 8 is present in the BST as right child of rootInp
    7 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 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
    10 min read
  • Binary Search Tree (BST) Traversals – Inorder, Preorder, Post Order
    Given a Binary Search Tree, The task is to print the elements in inorder, preorder, and postorder traversal of the Binary Search Tree.  Input:  Output: Inorder Traversal: 10 20 30 100 150 200 300Preorder Traversal: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 100 Input:  Output:
    11 min read
  • Balance a Binary Search Tree
    Given a BST (Binary Search Tree) that may be unbalanced, the task is to convert it into a balanced BST that has the minimum possible height. Examples: Input: Output: Explanation: The above unbalanced BST is converted to balanced with the minimum possible height. Input: Output: Explanation: The above
    10 min read
  • Self-Balancing Binary Search Trees
    Self-Balancing Binary Search Trees are height-balanced binary search trees that automatically keep the height as small as possible when insertion and deletion operations are performed on the tree. The height is typically maintained in order of logN so that all operations take O(logN) time on average
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences