Open In App

Binary Search Tree | Set 3 (Iterative Delete)

Improve
Improve
Like Article
Like
Save
Share
Report

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: 

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++




// C++ implementation to delete
// a node in the BST
 
#include <bits/stdc++.h>
using namespace std;
 
// Structure of the node
typedef struct treeNode {
    int data;
    struct treeNode* left;
    struct treeNode* right;
} treeNode;
 
// Utility function to print
// the inorder traversal of the BST.
void inorder(treeNode* root)
{
    if (root != NULL) {
        inorder(root->left);
        cout << root->data << ' ';
        inorder(root->right);
    }
}
 
// Utility function to insert
// nodes into our BST
treeNode* insert(treeNode* root, int key)
{
    // Check if tree is empty
    if (root == NULL) {
        treeNode* temp;
        temp = (treeNode*)malloc(sizeof(treeNode));
        temp->data = key;
        temp->left = NULL;
        temp->right = NULL;
        return temp;
    }
    if (key < root->data) {
 
        // if the key to be inserted
        // is lesser than the root,
        // insert into the left subtree,
        // and recursively call
        // the insert function with the
        // root->left as the new root.
        root->left = insert(root->left, key);
    }
    else {
 
        // if the key to be inserted
        // is greater than the root,
        // insert into the right subtree,
        // and recursively call
        // the insert function with the
        // root->right as the new root.
        root->right = insert(root->right, key);
    }
    return root;
}
 
// Iterative Function to delete
// 'key' from the BST.
treeNode* deleteIterative(treeNode* root, int key)
{
    treeNode* curr = root;
    treeNode* 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->data != key) {
        prev = curr;
        if (key < curr->data)
            curr = curr->left;
        else
            curr = curr->right;
    }
 
    if (curr == NULL) {
        cout << "Key " << key << " not found in the"
             << " provided BST.\n";
        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.
        treeNode* 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);
    }
 
    // node to be deleted has
    // two children.
    else {
        treeNode* p = NULL;
        treeNode* temp;
 
        // Compute the inorder successor
        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->data = temp->data;
        free(temp);
    }
    return root;
}
 
// Driver Code
int main()
{
    /*
         10
        /  \
       7    15
      / \   / \
      5  8 11 18
 
    */
    treeNode* root = NULL;
    root = insert(root, 10);
    root = insert(root, 7);
    root = insert(root, 5);
    root = insert(root, 8);
    root = insert(root, 15);
    root = insert(root, 11);
    root = insert(root, 18);
 
    cout << "Inorder traversal "
         << "of original BST:\n";
    inorder(root);
    cout << '\n';
 
    // delete node with data value 11 (leaf)
    root = deleteIterative(root, 11);
    cout << "\nDeletion of 11\n";
    cout << "Inorder traversal post deletion:\n";
    inorder(root);
    cout << '\n';
 
    // delete node with data value 15
    // (internal node with one child)
    root = deleteIterative(root, 15);
    cout << "\nDeletion of 15\n";
    cout << "Inorder traversal post deletion:\n";
    inorder(root);
    cout << '\n';
 
    // delete node with data value 10
    // (root, two children)
    root = deleteIterative(root, 10);
    cout << "\nDeletion of 10\n";
    cout << "Inorder traversal post deletion:\n";
    inorder(root);
    cout << '\n';
 
    return 0;
}


Java




// Java implementation to delete
// a node in the BST
 
public class GFG {
 
    // Structure of the node
    static class TreeNode {
        int data;
        TreeNode left;
        TreeNode right;
 
        TreeNode(int data) { this.data = data; }
    }
 
    // Utility function to print
    // the inorder traversal of the BST.
    static void inorder(TreeNode root)
    {
        if (root != null) {
            inorder(root.left);
            System.out.print(root.data + " ");
            inorder(root.right);
        }
    }
 
    // Utility function to insert
    // nodes into our BST
    static TreeNode insert(TreeNode root, int key)
    {
        // Check if tree is empty
        if (root == null) {
            TreeNode temp = new TreeNode(key);
            return temp;
        }
        if (key < root.data) {
 
            // if the key to be inserted
            // is lesser than the root,
            // insert into the left subtree,
            // and recursively call
            // the insert function with the
            // root.left as the new root.
            root.left = insert(root.left, key);
        }
        else {
 
            // if the key to be inserted
            // is greater than the root,
            // insert into the right subtree,
            // and recursively call
            // the insert function with the
            // root.right as the new root.
            root.right = insert(root.right, key);
        }
        return root;
    }
 
    // Iterative Function to delete
    // 'key' from the BST.
    static TreeNode deleteIterative(TreeNode root, int key)
    {
        TreeNode curr = root;
        TreeNode 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.data != key) {
            prev = curr;
            if (key < curr.data)
                curr = curr.left;
            else
                curr = curr.right;
        }
 
        if (curr == null) {
            System.out.println("Key " + key
                               + " not found in the"
                               + " provided BST.");
            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.
            TreeNode 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;
        }
 
        // node to be deleted has
        // two children.
        else {
            TreeNode p = null;
            TreeNode temp;
 
            // Compute the inorder successor
            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.data = temp.data;
        }
        return root;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        /*
                10
                / \
        7 15
        / \ / \
        5 8 11 18
 
         */
 
        TreeNode root = null;
        root = insert(root, 10);
        root = insert(root, 7);
        root = insert(root, 5);
        root = insert(root, 8);
        root = insert(root, 15);
        root = insert(root, 11);
        root = insert(root, 18);
 
        System.out.println(
            "Inorder traversal of original BST.");
        inorder(root);
        System.out.println("\n");
 
        // delete node with data value 11 (leaf)
        root = deleteIterative(root, 11);
        System.out.println("Deletion of 11");
        System.out.println(
            "Inorder traversal post deletion:");
        inorder(root);
        System.out.println("\n");
 
        // delete node with data value 15
        // (internal node with one child)
        root = deleteIterative(root, 15);
        System.out.println("Deletion of 15");
        System.out.println(
            "Inorder traversal post deletion:");
        inorder(root);
        System.out.println("\n");
 
        // delete node with data value 10
        // (root, two children)
        root = deleteIterative(root, 10);
        System.out.println("Deletion of 10");
        System.out.println(
            "Inorder traversal post deletion:");
        inorder(root);
        System.out.println("\n");
    }
}
 
// This code is contributed by Lovely Jain


Python3




# Python implementation to delete
# a node in the Binary Search Tree
 
# Class for a node of BST.
 
 
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# Utility function to print
# the inorder traversal of the BST
 
 
def inorder(root):
    if root != None:
        inorder(root.left)
        print(root.data, end=" ")
        inorder(root.right)
 
# Utility function to insert
# nodes into our BST
 
 
def insert(root, key):
    # check if tree is empty
    if root == None:
        temp = Node(key)
        return temp
 
    if key < root.data:
 
        """
        if the key to be inserted is
        lesser than the root,
        insert into the left subtree,
        and recursively call
        the insert function with
        the root.left as the new root.
        """
        root.left = insert(root.left, key)
 
    else:
        """
        if the key to be inserted is
        greater than the root,
        insert into the right subtree,
        and recursively call
        the insert function with the
        root->right as the new root.
        """
        root.right = insert(root.right, key)
 
    return root
 
# Iterative approach to
# delete 'key' from the BST.
 
 
def deleteIterative(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.data != key):
        prev = curr
        if curr.data < key:
            curr = curr.right
        else:
            curr = curr.left
 
    if curr == None:
        print("Key % d not found in\
           the provided BST." % key)
        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.data
        temp = None
 
    return root
 
# Function to create the BST
# and call the Delete Function
 
 
def main():
    """
         10        
        /   \        
       7     15    
      / \   / \    
      5 8  11 18    
    """
    root = None
    root = insert(root, 10)
    root = insert(root, 7)
    root = insert(root, 5)
    root = insert(root, 8)
    root = insert(root, 15)
    root = insert(root, 11)
    root = insert(root, 18)
 
    print("Inorder traversal of original BST:")
    inorder(root)
    print("\n")
 
    # delete node with data value 11 (leaf)
    root = deleteIterative(root, 11)
    print("Deletion of 11")
    print("Inorder traversal post deletion:")
    inorder(root)
    print("\n")
 
    # delete node with data value 15
    # (internal node with one child)
    root = deleteIterative(root, 15)
    print("Deletion of 15")
    print("Inorder traversal post deletion:")
    inorder(root)
    print("\n")
 
    # delete node with data value 10
    # (root, two children)
    root = deleteIterative(root, 10)
    print("Deletion of 10")
    print("Inorder traversal post deletion:")
    inorder(root)
    print()
 
 
# Driver Code
if __name__ == "__main__":
    main()


C#




// C# implementation to delete
// a node in the BST
using System;
 
// Structure of the node
public class TreeNode {
    public int data;
    public TreeNode left;
    public TreeNode right;
 
    public TreeNode(int key)
    {
        data = key;
        left = null;
        right = null;
    }
}
// Utility function to print
// the inorder traversal of the BST.
public class BinarySearchTree {
    public static void Inorder(TreeNode root)
    {
        if (root != null) {
            Inorder(root.left);
            Console.Write(root.data + " ");
            Inorder(root.right);
        }
    }
    // Utility function to insert
    // nodes into our BST
    public static TreeNode Insert(TreeNode root, int key)
    {
        // Check if tree is empty
        if (root == null) {
            return new TreeNode(key);
        }
        if (key < root.data) {
            // if the key to be inserted
            // is lesser than the root,
            // insert into the left subtree,
            // and recursively call
            // the insert function with the
            // root->left as the new root.
            root.left = Insert(root.left, key);
        }
        else {
            // if the key to be inserted
            // is greater than the root,
            // insert into the right subtree,
            // and recursively call
            // the insert function with the
            // root->right as the new root.
            root.right = Insert(root.right, key);
        }
        return root;
    }
    // Iterative Function to delete
    // 'key' from the BST.
    public static TreeNode DeleteIterative(TreeNode root,
                                           int key)
    {
        TreeNode curr = root;
        TreeNode 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.data != key) {
            prev = curr;
            if (key < curr.data) {
                curr = curr.left;
            }
            else {
                curr = curr.right;
            }
        }
 
        if (curr == null) {
            Console.WriteLine(
                "Key " + key
                + " not found in the provided BST.");
            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.
            TreeNode 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.
            curr = null;
        }
 
        // node to be deleted has
        // two children.
        else {
            TreeNode p = null;
            // Compute the inorder successor
            TreeNode 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.data = temp.data;
            temp = null;
        }
 
        return root;
    }
    // Driver Code
    public static void Main()
    {
        /*
        10
       /  \
      7    15
     / \   / \
     5  8 11 18
 
   */
        TreeNode root = null;
        root = Insert(root, 10);
        root = Insert(root, 7);
        root = Insert(root, 5);
        root = Insert(root, 8);
        root = Insert(root, 15);
        root = Insert(root, 11);
        root = Insert(root, 18);
 
        Console.WriteLine(
            "Inorder traversal of original BST:");
        Inorder(root);
        Console.WriteLine();
        // delete node with data value 11 (leaf)
        root = DeleteIterative(root, 11);
        Console.WriteLine("\nDeletion of 11");
        Console.WriteLine(
            "Inorder traversal post deletion:");
        Inorder(root);
        Console.WriteLine();
        // delete node with data value 15
        // (internal node with one child)
        root = DeleteIterative(root, 15);
        Console.WriteLine("\nDeletion of 15");
        Console.WriteLine(
            "Inorder traversal post deletion:");
        Inorder(root);
        Console.WriteLine();
        // delete node with data value 10
        // (root, two children)
        root = DeleteIterative(root, 10);
        Console.WriteLine("\nDeletion of 10");
        Console.WriteLine(
            "Inorder traversal post deletion:");
        Inorder(root);
        Console.WriteLine();
    }
}
// This code is contributed by NarasingaNikhil


Javascript




// C++ implementation to delete
// a node in the BST
 
// Structure of the node
 
class treeNode {
  constructor(data) {
    this.data = data;
    this.left = null;
    this.right = null;
  }
}
 
 
// Utility function to print
// the inorder traversal of the BST.
 
function inorder(root) {
  if (root !== null) {
    inorder(root.left);
    console.log(root.data + " ");
    inorder(root.right);
  }
}
 
// Utility function to insert
// nodes into our BST
 
function insert(root, key) {
 
       // Check if tree is empty
        
  if (root === null) {
    let temp = new treeNode(key);
    return temp;
  }
  if (key < root.data) {
       
        // if the key to be inserted
        // is lesser than the root,
        // insert into the left subtree,
        // and recursively call
        // the insert function with the
        // root->left as the new root.
         
    root.left = insert(root.left, key);
  } else {
   
      // if the key to be inserted
        // is greater than the root,
        // insert into the right subtree,
        // and recursively call
        // the insert function with the
        // root->right as the new root.
         
    root.right = insert(root.right, key);
  }
  return root;
}
 
// Iterative Function to delete
// 'key' from the BST.
 
function deleteIterative(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.data !== key) {
    prev = curr;
    if (key < curr.data) {
      curr = curr.left;
    } else {
      curr = curr.right;
    }
  }
 
  if (curr === null) {
    console.log("Key " + key + " not found in the provided BST.");
    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.
         
    let 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.
         
    curr = null;
  }
   
  // node to be deleted has
  // two children.
     
  else {
    let p = null;
    let 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.data = temp.data;
    temp = null;
  }
  return root;
}
 
// Driver Code
let root = null;
 
 
    /*
         10
        /  \
       7    15
      / \   / \
      5  8 11 18
 
    */
     
root = insert(root, 10);
root = insert(root, 7);
root = insert(root, 5);
root = insert(root, 8);
root = insert(root, 15);
root = insert(root, 11);
root = insert(root, 18);
 
console.log("Inorder traversal of original BST:");
inorder(root);
console.log("");
 
    // delete node with data value 11 (leaf)
     
root = deleteIterative(root, 11);
console.log("Deletion of 11");
console.log("Inorder traversal post deletion:");
inorder(root);
console.log("");
 
    // delete node with data value 15
    // (internal node with one child)
     
root = deleteIterative(root, 15);
console.log("Deletion of 15");
console.log("Inorder traversal post deletion:");
inorder(root);
console.log("");
 
 // delete node with data value 10
 // (root, two children)
root = deleteIterative(root, 10);
console.log("Deletion of 10");
console.log("Inorder traversal post deletion:");
inorder(root);
console.log("");
 
 
//This code is contributed by NarasingaNikhil


Output: 

Inorder traversal of original BST:
5 7 8 10 11 15 18 

Deletion of 11
Inorder traversal post deletion:
5 7 8 10 15 18 

Deletion of 15
Inorder traversal post deletion:
5 7 8 10 18 

Deletion of 10
Inorder traversal post deletion:
5 7 8 18

 



Last Updated : 15 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads