Deletion in a Binary Tree
Last Updated :
22 Oct, 2024
Given a binary tree, the task is to delete a given 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 : key = 10
Output:
Explanation: As the bottom & rightmost node in the above binary tree is 30 , replace the key node ie. 10 with 30 and remove the bottom & rightmost node.
Input : key = 20
Output:
Explanation: As the bottom & rightmost node in the above binary tree is 40, replace the key node ie. 20 with 40 and remove the bottom & rightmost node.
Approach:
The idea is to traverse the tree in level order manner. To perform the Deletion in a Binary Tree follow below:
- Starting at the root, find the deepest and rightmost node in the binary tree and the node which we want to delete.
- Replace the deepest rightmost node’s data with the node to be deleted.
- Then delete the deepest rightmost node.
Below is the illustration of above approach:
Below is the implementation of the above approach:
C++
// C++ program to delete a specific element
// in a binary tree
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
Node(int x){
data = x;
left = right = nullptr;
}
};
// Function to delete the deepest node in binary tree
void deletDeepest(Node* root, Node* dNode) {
queue<Node*> q;
q.push(root);
Node* curr;
while (!q.empty()) {
curr = q.front();
q.pop();
// If current node is the deepest
// node, delete it
if (curr == dNode) {
curr = nullptr;
delete (dNode);
return;
}
// Check the right child first
if (curr->right) {
// If right child is the deepest
// node, delete it
if (curr->right == dNode) {
curr->right = nullptr;
delete (dNode);
return;
}
q.push(curr->right);
}
// Check the left child
if (curr->left) {
// If left child is the deepest
// node, delete it
if (curr->left == dNode) {
curr->left = nullptr;
delete (dNode);
return;
}
q.push(curr->left);
}
}
}
// Function to delete the node with the given key
Node* deletion(Node* root, int key) {
// If the tree is empty, return null
if (root == nullptr)
return nullptr;
// If the tree has only one node
if (root->left == nullptr && root->right == nullptr) {
// If the root node is the key, delete it
if (root->data == key)
return nullptr;
else
return root;
}
queue<Node*> q;
q.push(root);
Node* curr;
Node* keyNode = nullptr;
// Level order traversal to find the deepest
// node and the key node
while (!q.empty()) {
curr = q.front();
q.pop();
// If current node is the key node
if (curr->data == key)
keyNode = curr;
if (curr->left)
q.push(curr->left);
if (curr->right)
q.push(curr->right);
}
// If key node is found, replace its data
// with the deepest node
if (keyNode != nullptr) {
// Store the data of the deepest node
int x = curr->data;
// Replace key node data with deepest
// node's data
keyNode->data = x;
// Delete the deepest node
deletDeepest(root, curr);
}
return root;
}
// Inorder traversal of a binary tree
void inorder(Node* curr) {
if (!curr)
return;
inorder(curr->left);
cout << curr->data << " ";
inorder(curr->right);
}
int main() {
// Construct the binary tree
// 10
// / \
// 11 9
// / \ / \
// 7 12 15 8
Node* root = new Node(10);
root->left = new Node(11);
root->right = new Node(9);
root->left->left = new Node(7);
root->left->right = new Node(12);
root->right->left = new Node(15);
root->right->right = new Node(8);
int key = 11;
root = deletion(root, key);
inorder(root);
return 0;
}
Java
// Java program to delete a specific
// element in a binary tree
import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// Function to delete the deepest node in
// binary tree
static void deletDeepest(Node root, Node dNode) {
Queue<Node> q = new LinkedList<>();
q.add(root);
Node curr;
while (!q.isEmpty()) {
curr = q.poll();
// If current node is the deepest
// node, delete it
if (curr == dNode) {
curr = null;
dNode = null;
return;
}
// Check the right child first
if (curr.right != null) {
// If right child is the deepest node,
// delete it
if (curr.right == dNode) {
curr.right = null;
dNode = null;
return;
}
q.add(curr.right);
}
// Check the left child
if (curr.left != null) {
// If left child is the deepest node,
// delete it
if (curr.left == dNode) {
curr.left = null;
dNode = null;
return;
}
q.add(curr.left);
}
}
}
// Function to delete the node with the given key
static Node deletion(Node root, int key) {
if (root == null)
return null;
// If the tree has only one node
if (root.left == null && root.right == null) {
// If the root node is the key,
// delete it
if (root.data == key)
return null;
else
return root;
}
Queue<Node> q = new LinkedList<>();
q.add(root);
Node curr = null;
Node keyNode = null;
// Level order traversal to find the
// deepest node and the key node
while (!q.isEmpty()) {
curr = q.poll();
// If current node is the key node
if (curr.data == key)
keyNode = curr;
if (curr.left != null)
q.add(curr.left);
if (curr.right != null)
q.add(curr.right);
}
// If key node is found, replace its
// data with the deepest node
if (keyNode != null) {
// Store the data of the
// deepest node
int x = curr.data;
// Replace key node data with
// deepest node's data
keyNode.data = x;
// Delete the deepest node
deletDeepest(root, curr);
}
return root;
}
// Inorder traversal of a binary tree
static void inorder(Node curr) {
if (curr == null)
return;
inorder(curr.left);
System.out.print(curr.data + " ");
inorder(curr.right);
}
public static void main(String[] args) {
// Construct the binary tree
// 10
// / \
// 11 9
// / \ / \
// 7 12 15 8
Node root = new Node(10);
root.left = new Node(11);
root.right = new Node(9);
root.left.left = new Node(7);
root.left.right = new Node(12);
root.right.left = new Node(15);
root.right.right = new Node(8);
int key = 11;
root = deletion(root, key);
inorder(root);
}
}
Python
# Python program to delete a specific
# element in a binary tree
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
# Function to delete the deepest node
# in the binary tree
def delete_deepest(root, dNode):
queue = [root]
while queue:
curr = queue.pop(0)
# If current node is the deepest
# node, delete it
if curr == dNode:
curr = None
del dNode
return
# Check the right child first
if curr.right:
# If right child is the deepest
# node, delete it
if curr.right == dNode:
curr.right = None
del dNode
return
queue.append(curr.right)
# Check the left child
if curr.left:
# If left child is the deepest
# node, delete it
if curr.left == dNode:
curr.left = None
del dNode
return
queue.append(curr.left)
# Function to delete the node with the given key
def deletion(root, key):
if root is None:
return None
# If the tree has only one node
if root.left is None and root.right is None:
if root.data == key:
return None
else:
return root
queue = [root]
curr = None
keyNode = None
# Level order traversal to find the
# deepest node and the key node
while queue:
curr = queue.pop(0)
# If current node is the key node
if curr.data == key:
keyNode = curr
if curr.left:
queue.append(curr.left)
if curr.right:
queue.append(curr.right)
# If key node is found, replace its
# data with the deepest node
if keyNode is not None:
x = curr.data
# Replace key node data with
# deepest node's data
keyNode.data = x
# Delete the deepest node
delete_deepest(root, curr)
return root
# Inorder traversal of a binary tree
def inorder(curr):
if curr is None:
return
inorder(curr.left)
print(curr.data, end=" ")
inorder(curr.right)
if __name__ == "__main__":
# Construct the binary tree
# 10
# / \
# 11 9
# / \ / \
# 7 12 15 8
root = Node(10)
root.left = Node(11)
root.right = Node(9)
root.left.left = Node(7)
root.left.right = Node(12)
root.right.left = Node(15)
root.right.right = Node(8)
key = 11
root = deletion(root, key)
inorder(root)
C#
// C# program to delete a specific
// element in a binary tree
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// Function to delete the deepest node in binary tree
static void deletDeepest(Node root, Node dNode) {
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
Node curr;
while (q.Count > 0) {
curr = q.Dequeue();
// If current node is the deepest
// node, delete it
if (curr == dNode) {
curr = null;
dNode = null;
return;
}
// Check the right child first
if (curr.right != null) {
if (curr.right == dNode) {
curr.right = null;
dNode = null;
return;
}
q.Enqueue(curr.right);
}
// Check the left child
if (curr.left != null) {
if (curr.left == dNode) {
curr.left = null;
dNode = null;
return;
}
q.Enqueue(curr.left);
}
}
}
// Function to delete the node with the given key
static Node deletion(Node root, int key) {
if (root == null)
return null;
// If the tree has only one node
if (root.left == null && root.right == null) {
if (root.data == key)
return null;
else
return root;
}
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
Node curr = null;
Node key_node = null;
// Level order traversal to find the
// deepest node and the key node
while (q.Count > 0) {
curr = q.Dequeue();
// If current node is the key node
if (curr.data == key)
key_node = curr;
if (curr.left != null)
q.Enqueue(curr.left);
if (curr.right != null)
q.Enqueue(curr.right);
}
// If key node is found, replace
// its data with the deepest node
if (key_node != null) {
// Store the data of the deepest node
int x = curr.data;
// Replace key node data with deepest
// node's data
key_node.data = x;
// Delete the deepest node
deletDeepest(root, curr);
}
return root;
}
// Inorder traversal of a binary tree
static void inorder(Node curr) {
if (curr == null)
return;
inorder(curr.left);
Console.Write(curr.data + " ");
inorder(curr.right);
}
static void Main(string[] args) {
// Construct the binary tree
// 10
// / \
// 11 9
// / \ / \
// 7 12 15 8
Node root = new Node(10);
root.left = new Node(11);
root.right = new Node(9);
root.left.left = new Node(7);
root.left.right = new Node(12);
root.right.left = new Node(15);
root.right.right = new Node(8);
int key = 11;
root = deletion(root, key);
inorder(root);
}
}
JavaScript
// JavaScript program to delete a specific
// element in a binary tree
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
// Function to delete the deepest node in
// a binary tree
function deleteDeepest(root, dNode) {
let queue = [];
queue.push(root);
while (queue.length !== 0) {
let curr = queue.shift();
// If current node is the deepest
// node, delete it
if (curr === dNode) {
curr = null;
return;
}
// Check the right child first
if (curr.right) {
if (curr.right === dNode) {
curr.right = null;
return;
} else {
queue.push(curr.right);
}
}
// Check the left child
if (curr.left) {
if (curr.left === dNode) {
curr.left = null;
return;
} else {
queue.push(curr.left);
}
}
}
}
// Function to delete the node with the given key
function deletion(root, key) {
if (root === null) return null;
// If the tree has only one node
if (root.left === null && root.right === null) {
if (root.data === key) return null;
else return root;
}
let queue = [];
queue.push(root);
let keyNode = null;
let curr = null;
// Level order traversal to find the
// deepest node and the key node
while (queue.length !== 0) {
curr = queue.shift();
// If current node is the key node
if (curr.data === key) keyNode = curr;
if (curr.left) queue.push(curr.left);
if (curr.right) queue.push(curr.right);
}
// If the key node is found, replace its data
// with the deepest node's data
if (keyNode !== null) {
// Store the deepest node's data
let x = curr.data;
// Replace the key node's data with the
// deepest node's data
keyNode.data = x;
// Delete the deepest node
deleteDeepest(root, curr);
}
return root;
}
// Inorder traversal of a binary tree
function inorder(curr) {
if (curr === null) return;
inorder(curr.left);
console.log(curr.data + " ");
inorder(curr.right);
}
// Construct the binary tree
let root = new Node(10);
root.left = new Node(11);
root.right = new Node(9);
root.left.left = new Node(7);
root.left.right = new Node(12);
root.right.left = new Node(15);
root.right.right = new Node(8);
let key = 11;
root = deletion(root, key);
inorder(root);
Time complexity: O(n), where n is number of nodes.
Auxiliary Space: O(n)
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.
Similar Reads
Binary Tree Data Structure A Binary Tree Data Structure is a hierarchical data structure in which each node has at most two children, referred to as the left child and the right child. It is commonly used in computer science for efficient storage and retrieval of data, with various operations such as insertion, deletion, and
3 min read
Introduction to Binary Tree Binary Tree is a non-linear and hierarchical data structure where each node has at most two children referred to as the left child and the right child. The topmost node in a binary tree is called the root, and the bottom-most nodes are called leaves. Introduction to Binary TreeRepresentation of Bina
15+ min read
Properties of Binary Tree This post explores the fundamental properties of a binary tree, covering its structure, characteristics, and key relationships between nodes, edges, height, and levelsBinary tree representationNote: Height of root node is considered as 0. Properties of Binary Trees1. Maximum Nodes at Level 'l'A bina
4 min read
Applications, Advantages and Disadvantages of Binary Tree A binary tree is a tree that has at most two children for any of its nodes. There are several types of binary trees. To learn more about them please refer to the article on "Types of binary tree" Applications:General ApplicationsDOM in HTML: Binary trees help manage the hierarchical structure of web
2 min read
Binary Tree (Array implementation) Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation o
6 min read
Maximum Depth of Binary Tree Given a binary tree, the task is to find the maximum depth of the tree. The maximum depth or height of the tree is the number of edges in the tree from the root to the deepest node.Examples:Input: Output: 2Explanation: The longest path from the root (node 12) goes through node 8 to node 5, which has
11 min read
Insertion in a Binary Tree in level order Given a binary tree and a key, the task is to insert the key into the binary tree at the first position available in level order manner.Examples:Input: key = 12 Output: Explanation: Node with value 12 is inserted into the binary tree at the first position available in level order manner.Approach:The
8 min read
Deletion in a Binary Tree Given a binary tree, the task is to delete a given 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 t
12 min read
Enumeration of Binary Trees A Binary Tree is labeled if every node is assigned a label and a Binary Tree is unlabelled if nodes are not assigned any label. Below two are considered same unlabelled trees o o / \ / \ o o o o Below two are considered different labelled trees A C / \ / \ B C A B How many different Unlabelled Binar
3 min read
Types of Binary Tree