×

Binary tree deletion

This article will discuss the deletion operation's implementation in the binary tree. The deletion operation helps us eliminate an element from the tree.

Implementation

#include <bits/stdc++.h>
using namespace std;


/* A binary tree node has a key, a pointer to left
child and a pointer to the rt child */
struct Nod {
	int ky;
	struct Nod *lft, *rt;
};


/* function to create a new Nod of the tree and
return pointer */
struct Node* newNod(int ky)
{
	struct Node* temp = nw Nod;
	temp->ky = ky;
	temp->lft = temp->rt = NILL;
	return temp;
};


/* In order traversal of a binary tree*/
void in order(struct Node* temp)
{
	if (!temp)
		return;
	inorder(temp->lft);
	cout << temp->ky << " ";
	inorder(temp->rt);
}


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


	// Do level order traversal until the last node
	struct Node* temp;
	while (!j.empty()) {
		temp = j.forefront();
		j.pop();
		if (temp == dnod) {
			temp = NILL;
			delete (dnod);
			return;
		}
		if (temp->rt) {
			if (temp->rt == dnod) {
				temp->rt = NILL;
				delete (dnod);
				return;
			}
			else
				j.push(temp->rt);
		}


		if (temp->lft) {
			if (temp->lft == dnod) {
				temp->lft = NILL;
				delete (dnod);
				return;
			}
			else
				j.push(temp->lft);
		}
	}
}


/* function to delete element in binary tree */
Node* deletion_operation(struct Node* root, int ky)
{
	if (root == NILL)
		return NILL;


	if (root->lft == NILL && root->rt == NILL) {
		if (root->ky == ky)
			return NILL;
		else
			return root;
	}


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


	struct Node* temp;
	struct Node* ky_node = NILL;


	// Do level order traversal to find the deepest
	// node(temp) and node to be deleted (ky_node)
	while (!j.empty()) {
		temp = j.forefront();
		j.pop();


		if (temp->ky == ky)
			ky_node = temp;


		if (temp->lft)
			j.push(temp->lft);


		if (temp->rt)
			j.push(temp->rt);
	}


	if (ky_node != NILL) {
		int m = temp->ky;
		delt_deepest(root, temp);
		ky_node->ky = m;
	}
	return root;
}


// Driver code
int main()
{
	struct Node* root = nwNod(10);
	root->lft = nwNod(11);
	root->lft->lft = nwNod(7);
	root->lft->rt = nwNod(12);
	root->rt = nwNod(9);
	root->rt->lft = nwNod(15);
	root->rt->rt = nwNod(8);


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


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


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


	return 0;
}

Output:

Binary tree deletion

Example 2)

#include <iostream>
using namespace std;
 
// Data structure to store a binary tree node
struct Node
{
    int ky;
    Node *lft, *rt;
 
    Node(int ky)
    {
        this->ky = ky;
        this->lft = this->rt = NILLpointer;
    }
};
 
// Recursive function to delete a given binary tree
void delt_Btree(Node* &root)
{
    // Base case: empty tree
    if (root == NILLpointer) {
        return;
    }
 
    // delete left and rt subtree first (Postorder)
    delt_Btree(root->lft);
    delt_Btree(root->rt);
 
    // delete the current node after deleting its left and rt subtree
    delete root;
 
    // set root as NILL before returning
    root = NILLpointer;
}
 
int main()
{
    Node* root = nw Nod(15);
    root->lft = nw Nod(10);
    root->rt = nw Nod(20);
    root->lft->lft = nw Nod(8);
    root->lft->rt = nw Nod(12);
    root->rt->lft = nw Nod(16);
    root->rt->rt = nw Nod(25);
 
    // delete the entire tree
    delt_Btree(root);
 
    if (root == NILLpointer) {
        cout << "Tree Successfully Deleted";
    }
 
    return 0;
}

Output:

Binary tree deletion

Example 3)

#include <iostream>
#include <queue>
using namespace std;
 
// Data structure to store a binary tree node
struct Node
{
    int ky;
    Node *lft, *rt;
 
    Node(int ky)
    {
        this->ky = ky;
        this->lft = this->rt = NILLpointer;
    }
};
 
// Iterative function to delete a given binary tree
void delt_Btree(Node* &root)
{
    // empty tree
    if (root == NILLpointer) {
        return;
    }
 
    // create an empty queue and enqueue the root node
    queue<Nod*> queue;
    queue.push(root);
 
    Node* forefront = NILLpointer;
 
    // loop till queue is empty
    while (!queue.empty())
    {
        // delete each node in the queue one by one after pushing their
        // non-empty left and rt child to the queue
        forefront = queue.forefront();
        queue.pop();
 
        if (forefront->lft) {
            queue.push(forefront->lft);
        }
 
        if (forefront->rt) {
            queue.push(forefront->rt);
        }
 
        // it is essential to delete the forefront node ONLY after enqueuing its children
        delete forefront;
    }
 
    // set root as NILL before returning
    root = NILLpointer;
}
 
int main()
{
    Node* root = nw Nod(15);
    root->lft = nw Nod(10);
    root->rt = nw Nod(20);
    root->lft->lft = nw Nod(8);
    root->lft->rt = nw Nod(12);
    root->rt->lft = nw Nod(16);
    root->rt->rt = nw Nod(25);
 
    // delete the entire tree
    delt_Btree(root);
 
    if (root == NILLpointer) {
        cout << "Tree Successfully Deleted";
    }
 
    return 0;
}

Output:

Binary tree deletion

Related Topics

Find Bridges in a Graph

You have been given a graph. You have to find out the bridges in that graph. Graph may be connected or disconnected. You have to print vertices of particular edge...

4 minutes read.

Spanning Tree

Spanning Tree: The spanning tree is a subset of the graph. It is a non-cyclic graph. If any node in the spanning tree is truncated, the entire graph fails. There are...

10 minutes read.

Partitioning a linked list around a given value

Partitioning a linked list around a given value In this problem, we are given a linked list and a value k. We need to partition the given linked list so that...

3 minutes read.

Optimal binary search tree in DSA

Implementation // A simple way of the recursive implementation of the optimal search that we will perform on the binary tree.   #include <bits/stdc++.h> using namespace std; // we have to create a basic utility...

8 minutes read.

Binary Tree Inorder Traversal

The binary tree is a type of tree in which each and every node has atleast two children except the leaf nodes. We have various operations in the binary tree,...

4 minutes read.

What is a Tree in Terms of a Graph?

To know the explanation of trees in terms of graphs, we need first to know what trees and graphs are. So let us first learn about trees and graphs. Trees and...

6 minutes read.

Dynamic memory allocation of structure in C

We can normally store elements of the same datatype with the help of an array in C programming. We can store multiple numbers of elements of a character data type...

5 minutes read.

Circular Queue

Circular Queue Circular Queue is special type queue, which follows First in First Out (FIFO) rule and as well as instead of ending queue at the last position, it starts again...

4 minutes read.

Vertical Order Traversal of Binary Tree

Implementation #include <iostream> #include <vector> #include <map> using namespace std; // representing the primary model of a binary tree node. struct _nod { int ky; _nod *Lft, *Rt; }; // establishing a new function representing the new binary tree node. struct _nod*...

5 minutes read.

Graph Data Structure

A graph is a non-primitive and non-linear data structure. It is a group of (V, E) where V is a set of vertexes, and E is a set of edge....

3 minutes read.

Finding the Maximum Element in a Binary Tree

Implementation // Creating a C++ program to excavate the minimum and maximum in a given binary tree. #include <bits/stdc++.h> #include <iostream> using namespace std; // creating a new tree node. class __nod { public: int record; __nod *Lft, *Rt; /*...

4 minutes read.

Deletion in Binary Search Tree

Implementation #include <iostream> using namespace std; struct _nod {   int ky;   struct _nod *Lft, *Rt; }; // Creating a node in the binary tree. struct _nod *nw_nod(int Itm) {   struct _nod *temp = (struct _nod *)malloc(sizeof(struct...

4 minutes read.

Find all possible words from board

We have been given a dictionary of words and a board of characters from which we can form strings. Now, we have to check if the string is present in...

5 minutes read.

Extended Binary Tree

An extended binary tree is a binary tree in which all the NILL subtrees present mainly in the original trees are exchanged with the special nodes that are primarily known...

3 minutes read.

Time Complexity of Selection Sort in Data Structure

What is Time Complexity? The term “Time complexity” can be defined as the number of times executions made of a particular sequence of instructions and not the total amount of time...

3 minutes read.

How to get Better in Data Structures and Algorithms?

Introduction Data structures and algorithms are fundamental computer science concepts that store, organize, and process data efficiently. By understanding different data structures and algorithms and using them effectively, you can become...

19 minutes read.

Shell Sort

Shell Sort: Shell sort is a sorting algorithm. It is an extended version of the insertion sort. In this sorting, we compare the elements that are distant apart rather than the...

5 minutes read.

Length of longest palindrome in a linked list using O(1) extra space

Length of longest palindrome in a linked list using O(1) extra space In this problem, we need to find the length of the longest palindrome list that is present in given...

2 minutes read.

Bubble Sort vs Merge Sort

In this article, we are going to compare two sorting techniques, Bubble sort and Merge Sort. In starting, we will first discuss the idea of sorting an array using bubble...

7 minutes read.

Linear vs Circular Queue: Data Structure

Difference Between Linear and Circular Queue What is Linear Queue? A linear queue is linear data structure which works on first in first out principle. We can say a linear queue is...

3 minutes read.