The Wayback Machine - https://web.archive.org/web/20240926192057/https://www.geeksforgeeks.org/deletion-binary-tree/
Open In App

Deletion in a Binary Tree

Last Updated : 03 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Easy
22.28%
21.2K

Given a binary tree, delete a node from it by making sure that the tree shrinks from the bottom (i.e. the deleted node is replaced by the bottom-most and rightmost node). This is different from BST deletion. Here we do not have any order among elements, so we replace them with the last element.

Examples :

Input : Delete 10 in below tree

       10
     /    \         
  20     30

Output:    
       30
     /             
 20     

Input : Delete 20 in below tree
       10
     /    \         
 20     30
            \
            40

Output:    
       10
   /      \             
40        30
            

Algorithm:

  1. Starting at the root, find the deepest and rightmost node in the binary tree and the node which we want to delete. 
  2. Replace the deepest rightmost node’s data with the node to be deleted. 
  3. Then delete the deepest rightmost node.

Below is the implementation of the above approach:

C++
// C++ program to delete element in binary tree
#include <bits/stdc++.h>
using namespace std;

/* A binary tree node has key, pointer to left
child and a pointer to right child */
struct Node {
    int key;
    struct Node *left, *right;
};

/* function to create a new node of tree and
return pointer */
struct Node* newNode(int key)
{
    struct Node* temp = new Node;
    temp->key = key;
    temp->left = temp->right = NULL;
    return temp;
};

/* Inorder traversal of a binary tree*/
void inorder(struct Node* temp)
{
    if (!temp)
        return;
    inorder(temp->left);
    cout << temp->key << " ";
    inorder(temp->right);
}

/* function to delete the given deepest node
(d_node) in binary tree */
void deletDeepest(struct Node* root, struct Node* d_node)
{
    queue<struct Node*> q;
    q.push(root);

    // Do level order traversal until last node
    struct Node* temp;
    while (!q.empty()) {
        temp = q.front();
        q.pop();
        if (temp == d_node) {
            temp = NULL;
            delete (d_node);
            return;
        }
        if (temp->right) {
            if (temp->right == d_node) {
                temp->right = NULL;
                delete (d_node);
                return;
            }
            else
                q.push(temp->right);
        }

        if (temp->left) {
            if (temp->left == d_node) {
                temp->left = NULL;
                delete (d_node);
                return;
            }
            else
                q.push(temp->left);
        }
    }
}

/* function to delete element in binary tree */
Node* deletion(struct Node* root, int key)
{
    if (root == NULL)
        return NULL;

    if (root->left == NULL && root->right == NULL) {
        if (root->key == key)
            return NULL;
        else
            return root;
    }

    queue<struct Node*> q;
    q.push(root);

    struct Node* temp;
    struct Node* key_node = NULL;

    // Do level order traversal to find deepest
    // node(temp) and node to be deleted (key_node)
    while (!q.empty()) {
        temp = q.front();
        q.pop();

        if (temp->key == key)
            key_node = temp;

        if (temp->left)
            q.push(temp->left);

        if (temp->right)
            q.push(temp->right);
    }

    if (key_node != NULL) {
        int x = temp->key;
        key_node->key = x;
        deletDeepest(root, temp);
    }
    return root;
}

// Driver code
int main()
{
    struct Node* root = newNode(10);
    root->left = newNode(11);
    root->left->left = newNode(7);
    root->left->right = newNode(12);
    root->right = newNode(9);
    root->right->left = newNode(15);
    root->right->right = newNode(8);

    cout << "Inorder traversal before deletion: ";
    inorder(root);

    int key = 11;
    root = deletion(root, key);

    cout << endl;
    cout << "Inorder traversal after deletion: ";
    inorder(root);

    return 0;
}
Java
// Java program to delete element
// in binary tree
import java.util.LinkedList;
import java.util.Queue;

class GFG {

    // A binary tree node has key, pointer to
    // left child and a pointer to right child
    static class Node {
        int key;
        Node left, right;

        // Constructor
        Node(int key)
        {
            this.key = key;
            left = null;
            right = null;
        }
    }

    static Node root;
    static Node temp = root;

    // Inorder traversal of a binary tree
    static void inorder(Node temp)
    {
        if (temp == null)
            return;

        inorder(temp.left);
        System.out.print(temp.key + " ");
        inorder(temp.right);
    }

    // Function to delete deepest
    // element in binary tree
    static void deleteDeepest(Node root, Node delNode)
    {
        Queue<Node> q = new LinkedList<Node>();
        q.add(root);

        Node temp = null;

        // Do level order traversal until last node
        while (!q.isEmpty()) {
            temp = q.peek();
            q.remove();

            if (temp == delNode) {
                temp = null;
                return;
            }
            if (temp.right != null) {
                if (temp.right == delNode) {
                    temp.right = null;
                    return;
                }
                else
                    q.add(temp.right);
            }

            if (temp.left != null) {
                if (temp.left == delNode) {
                    temp.left = null;
                    return;
                }
                else
                    q.add(temp.left);
            }
        }
    }

    // Function to delete given element
    // in binary tree
    static void delete(Node root, int key)
    {
        if (root == null)
            return;

        if (root.left == null && root.right == null) {
            if (root.key == key) {
                root = null;
                return;
            }
            else
                return;
        }

        Queue<Node> q = new LinkedList<Node>();
        q.add(root);
        Node temp = null, keyNode = null;

        // Do level order traversal until
        // we find key and last node.
        while (!q.isEmpty()) {
            temp = q.peek();
            q.remove();

            if (temp.key == key)
                keyNode = temp;

            if (temp.left != null)
                q.add(temp.left);

            if (temp.right != null)
                q.add(temp.right);
        }

        if (keyNode != null) {
            int x = temp.key;
            keyNode.key = x;
            deleteDeepest(root, temp);
        }
    }

    // Driver code
    public static void main(String args[])
    {
        root = new Node(10);
        root.left = new Node(11);
        root.left.left = new Node(7);
        root.left.right = new Node(12);
        root.right = new Node(9);
        root.right.left = new Node(15);
        root.right.right = new Node(8);

        System.out.print("Inorder traversal "
                         + "before deletion:");
        inorder(root);

        int key = 11;
        delete(root, key);

        System.out.print("\nInorder traversal "
                         + "after deletion:");
        inorder(root);
    }
}

// This code is contributed by Ravi Kant Verma
Python
# Python3 program to illustrate deletion in a Binary Tree

# class to create a node with data, left child and right child.


class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

# Inorder traversal of a binary tree


def inorder(temp):
    if(not temp):
        return
    inorder(temp.left)
    print(temp.data, end=" ")
    inorder(temp.right)

# function to delete the given deepest node (d_node) in binary tree


def deleteDeepest(root, d_node):
    q = []
    q.append(root)
    while(len(q)):
        temp = q.pop(0)
        if temp is d_node:
            temp = None
            return
        if temp.right:
            if temp.right is d_node:
                temp.right = None
                return
            else:
                q.append(temp.right)
        if temp.left:
            if temp.left is d_node:
                temp.left = None
                return
            else:
                q.append(temp.left)

# function to delete element in binary tree


def deletion(root, key):
    if root == None:
        return None
    if root.left == None and root.right == None:
        if root.key == key:
            return None
        else:
            return root
    key_node = None
    q = []
    q.append(root)
    temp = None
    while(len(q)):
        temp = q.pop(0)
        if temp.data == key:
            key_node = temp
        if temp.left:
            q.append(temp.left)
        if temp.right:
            q.append(temp.right)
    if key_node:
        x = temp.data
        key_node.data = x
        deleteDeepest(root, temp)
    return root


# Driver code
if __name__ == '__main__':
    root = Node(10)
    root.left = Node(11)
    root.left.left = Node(7)
    root.left.right = Node(12)
    root.right = Node(9)
    root.right.left = Node(15)
    root.right.right = Node(8)
    print("The tree before the deletion: ", end="")
    inorder(root)
    key = 11
    root = deletion(root, key)
    print()
    print("The tree after the deletion: ", end="")
    inorder(root)

# This code is contributed by Monika Anandan
C#
// C# program to delete element
// in binary tree

using System;
using System.Collections.Generic;

class GFG {

    // A binary tree node has key, pointer to
    // left child and a pointer to right child
    public class Node {
        public int key;
        public Node left, right;

        // Constructor
        public Node(int key)
        {
            this.key = key;
            left = null;
            right = null;
        }
    }

    static Node root;

    // Inorder traversal of a binary tree
    static void inorder(Node temp)
    {
        if (temp == null)
            return;

        inorder(temp.left);
        Console.Write(temp.key + " ");
        inorder(temp.right);
    }

    // Function to delete deepest
    // element in binary tree
    static void deleteDeepest(Node root, Node delNode)
    {
        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);

        Node temp = null;

        // Do level order traversal until last node
        while (q.Count != 0) {
            temp = q.Peek();
            q.Dequeue();

            if (temp == delNode) {
                temp = null;
                return;
            }
            if (temp.right != null) {
                if (temp.right == delNode) {
                    temp.right = null;
                    return;
                }

                else
                    q.Enqueue(temp.right);
            }

            if (temp.left != null) {
                if (temp.left == delNode) {
                    temp.left = null;
                    return;
                }
                else
                    q.Enqueue(temp.left);
            }
        }
    }

    // Function to delete given element
    // in binary tree
    static void delete(Node root, int key)
    {
        if (root == null)
            return;

        if (root.left == null && root.right == null) {
            if (root.key == key) {
                root = null;
                return;
            }
            else
                return;
        }

        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);
        Node temp = null, keyNode = null;

        // Do level order traversal until
        // we find key and last node.
        while (q.Count != 0) {
            temp = q.Peek();
            q.Dequeue();

            if (temp.key == key)
                keyNode = temp;

            if (temp.left != null)
                q.Enqueue(temp.left);

            if (temp.right != null)
                q.Enqueue(temp.right);
        }

        if (keyNode != null) {
            int x = temp.key;
            keyNode.key = x;
            deleteDeepest(root, temp);
        }
    }

    // Driver code
    public static void Main(String[] args)
    {
        root = new Node(10);
        root.left = new Node(11);
        root.left.left = new Node(7);
        root.left.right = new Node(12);
        root.right = new Node(9);
        root.right.left = new Node(15);
        root.right.right = new Node(8);

        Console.Write("Inorder traversal "
                      + "before deletion: ");
        inorder(root);

        int key = 11;
        delete(root, key);

        Console.Write("\nInorder traversal "
                      + "after deletion: ");
        inorder(root);
    }
}

// This code is contributed by Abhijeet Kumar(abhijeet19403)
JavaScript
    // Javascript program to delete element in binary tree
    
    class Node
    {
        constructor(key) {
           this.left = null;
           this.right = null;
           this.key = key;
        }
    }
    
    let root;
    let temp = root;

    // Inorder traversal of a binary tree
    function inorder(temp)
    {
        if (temp == null)
            return;

        inorder(temp.left);
        console.log(temp.key + " ");
        inorder(temp.right);
    }

    // Function to delete deepest
    // element in binary tree
    function deleteDeepest(root, delNode)
    {
        let q = [];
        q.push(root);

        let temp = null;

        // Do level order traversal until last node
        while (q.length > 0)
        {
            temp = q[0];
            q.shift();

            if (temp == delNode)
            {
                temp = null;
                return;

            }
            if (temp.right!=null)
            {
                if (temp.right == delNode)
                {
                    temp.right = null;
                    return;
                }
                else
                    q.push(temp.right);
            }

            if (temp.left != null)
            {
                if (temp.left == delNode)
                {
                    temp.left = null;
                    return;
                }
                else
                    q.push(temp.left);
            }
        }
    }

    // Function to delete given element
    // in binary tree
    function Delete(root, key)
    {
        if (root == null)
            return;

        if (root.left == null &&
           root.right == null)
        {
            if (root.key == key)
            {
                  root=null;
                  return;
            }
            else
                return;
        }

        let q = [];
        q.push(root);
        let temp = null, keyNode = null;

        // Do level order traversal until
        // we find key and last node.
        while (q.length > 0)
        {
            temp = q[0];
            q.shift();

            if (temp.key == key)
                keyNode = temp;

            if (temp.left != null)
                q.push(temp.left);

            if (temp.right != null)
                q.push(temp.right);
        }

        if (keyNode != null)
        {
            let x = temp.key;
            keyNode.key = x;
            deleteDeepest(root, temp);
        }
    }
    
    root = new Node(10);
    root.left = new Node(11);
    root.left.left = new Node(7);
    root.left.right = new Node(12);
    root.right = new Node(9);
    root.right.left = new Node(15);
    root.right.right = new Node(8);
 
    console.log("Inorder traversal " +
                     "before deletion: ");
    inorder(root);
 
    let key = 11;
    Delete(root, key);
 
    console.log("</br>" + "Inorder traversal " +
                     "after deletion: ");
    inorder(root);

Output
Inorder traversal before deletion : 7 11 12 10 15 9 8 
Inorder traversal after deletion : 7 8 12 10 15 9 

Time complexity: O(n) where n is no number of nodes
Auxiliary Space: O(n) size of queue

Note: We can also replace the node’s data that is to be deleted with any node whose left and right child points to NULL but we only use deepest node in order to maintain the Balance of a binary tree.



Previous Article
Next Article

Similar Reads

Threaded Binary Search Tree | Deletion
A threaded binary tree node looks like following. C/C++ Code 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 Code static class Node { Node left, right; int info; // Tru
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 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 b
10 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
m-Way Search Tree | Set-2 | Insertion and Deletion
Insertion in an m-Way search tree: The insertion in an m-Way search tree is similar to binary trees but there should be no more than m-1 elements in a node. If the node is full then a child node will be created to insert the further elements. Let us see the example given below to insert an element in an m-Way search tree.Example: To insert a new el
15+ min read
Minimize deletion of edges to convert Tree into a forest of size at most N/2
Given a tree with N nodes, numbered from 0 to N - 1, the task is to find the minimum number of deletion of edges, such that, the tree is converted into a forest where each tree in the forest can have size less than equal to ⌊N/2⌋. Examples: Input: N = 3, edges = [[0, 1], [0, 2]] 0 / \ 1 2Output: 2Explanation: The maximum size of each tree after rem
14 min read
Van Emde Boas Tree | Set 4 | Deletion
It is highly recommended to read the previous articles on Van Emde Boas Tree first. Procedure for Delete: Here we are assuming that the key is already present in the tree. First we check if only one key is present, then assign the maximum and minimum of the tree to null value to delete the key.Base Case: If the universe size of the tree is two then
15+ min read
Deletion in Red-Black Tree
Deletion in a red-black tree is a bit more complicated than insertion. When a node is to be deleted, it can either have no children, one child or two children. Here are the steps involved in deleting a node in a red-black tree:If the node to be deleted has no children, simply remove it and update the parent node.If the node to be deleted has only o
15+ min read
Deletion in K Dimensional Tree
We strongly recommend to refer below posts as a prerequisite of this.K Dimensional Tree | Set 1 (Search and Insert) K Dimensional Tree | Set 2 (Find Minimum)In this post delete is discussed. The operation is to delete a given point from K D Tree. Like Binary Search Tree Delete, we recursively traverse down and search for the point to be deleted. Be
15+ min read
Ternary Search Tree (Deletion)
In the SET 1 post on TST we have described how to insert and search a node in TST. In this article, we will discuss algorithm on how to delete a node from TST. During delete operation we delete the key in bottom-up manner using recursion. The following are possible cases when deleting a key from trie. Key may not be there in TST. Solution: Delete o
14 min read
Deletion in Splay Tree
It is recommended to refer following post as prerequisite of this post. Splay Tree | Set 1 (Search) Following are the different cases to delete a key k from splay tree. If Root is NULL: We simply return the root.Else Splay the given key k. If k is present, then it becomes the new root. If not present, then last accessed leaf node becomes the new ro
15+ min read
Deletion in B+ Tree
B + tree is a variation of the B-tree data structure. In a B + tree, data pointers are stored only at the leaf nodes of the tree. In a B+ tree structure of a leaf node differs from the structure of internal nodes. When compared to the B tree, B+ Tree offers more effective insertion, deletion, and other operations. Deleting in B+ Tree: Three operati
15+ min read
Deletion in an AVL Tree
We have discussed AVL insertion in the previous post. In this post, we will follow a similar approach for deletion. Steps to follow for deletion. To make sure that the given tree remains AVL after every deletion, we must augment the standard BST delete operation to perform some re-balancing. Following are two basic operations that can be performed
15+ min read
Convert a Generic Tree(N-array Tree) to Binary Tree
Prerequisite: Generic Trees(N-array Trees) In this article, we will discuss the conversion of the Generic Tree to a Binary Tree. Following are the rules to convert a Generic(N-array Tree) to a Binary Tree: The root of the Binary Tree is the Root of the Generic Tree.The left child of a node in the Generic Tree is the Left child of that node in the B
13 min read
Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
We have discussed Threaded Binary Tree. The idea of threaded binary trees is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a right pointer is NULL, it is used to store inorder successor. The following diagram sho
12 min read
Check whether a binary tree is a full binary tree or not | Iterative Approach
Given a binary tree containing n nodes. The problem is to check whether the given binary tree is a full binary tree or not. A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has only one child node. Examples: Input : 1 / \ 2 3 / \ 4 5 Outp
8 min read
Binary Tree to Binary Search Tree Conversion using STL set
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree.This solution will use Sets of C++ STL instead of array-based solution. Examples: Example 1 Input: 10 / \ 2 7 / \ 8 4 Output: 8 / \ 4 10 / \ 2 7 Example 2 Input: 10 / \ 30 15 / \ 20 5 Output: 15 / \
12 min read
Check whether a given binary tree is skewed binary tree or not?
Given a Binary Tree check whether it is skewed binary tree or not. A skewed tree is a tree where each node has only one child node or none. Examples: Input : 5 / 4 \ 3 / 2 Output : Yes Input : 5 / 4 \ 3 / \ 2 4 Output : No The idea is to check if a node has two children. If node has two children return false, else recursively compute whether subtre
13 min read
Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
Given two binary trees S and T, the task is the check that if S is a subtree of the Tree T. For Example: Input: Tree T - 1 / \ 2 3 / \ / \ 4 5 6 7 Tree S - 2 / \ 4 5 Output: YES Explanation: The above tree is the subtree of the tree T, Hence the output is YES Approach: The idea is to traverse both the tree in Pre-order Traversal and check for each
11 min read
Check if a Binary tree is Subtree of another Binary tree | Set 3
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree. Examples: Input: Tree-T Tree-S 1 3 / \ / 2
15 min read
Check whether a binary tree is a full binary tree or not
A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has one child node. More information about full binary trees can be found here. For Example : Recommended PracticeFull binary treeTry It! To check whether a binary tree is a full binary tre
14 min read
Check if a binary tree is subtree of another binary tree | Set 2
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree.For example, in the following case, Tree1 i
15+ min read
Minimum swap required to convert binary tree to binary search tree
Given the array representation of Complete Binary Tree i.e, if index i is the parent, index 2*i + 1 is the left child and index 2*i + 2 is the right child. The task is to find the minimum number of swap required to convert it into Binary Search Tree. Examples: Input : arr[] = { 5, 6, 7, 8, 9, 10, 11 } Output : 3 Binary tree of the given array: Swap
8 min read
Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
Idea of Threaded Binary Tree is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a right pointer is NULL, it is used to store inorder successor. Following diagram shows an example Single Threaded Binary Tree. The do
12 min read
Binary Tree to Binary Search Tree Conversion
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of Binary Tree. Examples Example 1Input: 10 / \ 2 7 / \ 8 4Output: 8 / \ 4 10 / \ 2 7Example 2Input: 10 / \ 30 15 / \ 20 5Output: 15 / \ 10 20 / \ 5 30Solution: Following is a 3 step solution for converting Binary tre
15+ min read
Check if a Binary Tree is subtree of another binary tree | Set 1
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree. Examples: Input: Tree S 10 / \ 4 6 \ 30 Tr
11 min read
Difference between Binary Tree and Binary Search Tree
Binary Tree Data Structure:A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right children. Binary Search Tree Data Structure (BST):A binary search tree is a hierarchical data structure where each node has at most two children, wi
2 min read
String slicing in Python to check if a string can become empty by recursive deletion
Given a string “str” and another string “sub_str”. We are allowed to delete “sub_str” from “str” any number of times. It is also given that the “sub_str” appears only once at a time. The task is to find if “str” can become empty by removing “sub_str” again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
2 min read
Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
Given two strings, find if we can make first string from second by deleting some characters from second and rearranging remaining characters. Examples: Input : s1 = ABHISHEKsinGH : s2 = gfhfBHkooIHnfndSHEKsiAnG Output : Possible Input : s1 = Hello : s2 = dnaKfhelddf Output : Not Possible Input : s1 = GeeksforGeeks : s2 = rteksfoGrdsskGeggehes Outpu
2 min read
2-3 Trees | (Search, Insert and Deletion)
In binary search trees we have seen the average-case time for operations like search/insert/delete is O(log N) and the worst-case time is O(N) where N is the number of nodes in the tree. Like other Trees include AVL trees, Red Black Tree, B tree, 2-3 Tree is also a height balanced tree. The time complexity of search/insert/delete is O(log N) . A 2-
4 min read
Fibonacci Heap - Deletion, Extract min and Decrease key
In the last post, we discussed the Insertion and Union of Fibonacci Heaps. In this post, we will discuss Extract_min(), Decrease_key() and Deletion() operations on Fibonacci heap. Prerequisites: Fibonacci Heap (Introduction) Fibonacci Heap - Insertion and Union Extract_min(): We create a function for deleting the minimum node and setting the min po
12 min read
Practice Tags :