×

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

Finding the Sum of All Paths in a Binary Tree

Implementation // Writing the C++ program to implement the below approach.  #include <bits/stdc++.h> using namespace std; // creating the new tree node structure. struct Tree__nod { int val; Tree__nod *Lft, *Rt; }; // creating a new function that will...

8 minutes read.

Horizontal and Vertical Scaling

Being a software engineer, you would have designed a website or application and deployed it on any server. Imagine that the developed application starts getting popular, and many users engage...

6 minutes read.

Binary Search Tree vs AVL Tree: Data Structure

Difference Between Binary Search Tree and AVL Tree Binary Search Tree: The binary search tree is a kind of binary tree data structure and it follows the conditions of binary...

3 minutes read.

Rearrange a linked list into alternate fashion first and the last element

Rearrange a linked list into alternate fashion first and the last element This article will explain how to rearrange the linked list into alternate fashion first and the last element. Here,...

3 minutes read.

Object-Oriented Analysis and Design

While designing a system, one should know all the requirements or needs of the plan beforehand, and to do so, we should use a systematic approach to analyze the goal...

3 minutes read.

String Operations in Data Structures

Operations on Strings Reversing the order of words in a sentence Reversing a string is a technique that reverses or alters the order of a given string so that the last character...

9 minutes read.

Convert Binary Tree into a Threaded Binary Tree

Implementation /*Writing a C++ program that will help us change the binary tree into a threaded binary tree and help us transform. */ #include <bits/stdc++.h> using namespace std; /*Creating the structure of a node...

11 minutes read.

Strings in Data Structures

Strings and functions in C A string is a collection of characters. We'll learn how to declare strings, operate with strings in C programming, and use pre-defined string handling routines. We'll look...

7 minutes read.

Given a Binary Tree Check the Zig-Zag Traversal

Implementation // The C++ implementation of the zig-zag traversal method in the O(n) time.  #include <iostream> #include <stack> using namespace std; // creating a binary tree node. struct __nod { int record; struct __nod *Lft, *Rt; }; // creating a...

4 minutes read.

Bottom view of the binary tree

The bottom of the binary tree is generally defined as the number of nods present in the bottom-most part of the tree. In this article, we will see the implementation...

3 minutes read.

Selection Sort

In each iteration of the selection sort algorithm, the smallest item from an unsorted list is chosen and placed at the top of the unsorted list. Algorithm of Selection Sorting In order...

3 minutes read.

Segregate Even and Odd nodes in a Linked List

Segregate even and odd nodes in a Linked List In this problem, we have given a linked list with integer numbers. We need to modify the given linked list in such...

4 minutes read.

Big O Notations

What is Big O Notation, and why is it important? "Big O notation is a mathematical notation that depicts a function's limiting behaviour when the input tends towards a certain value...

10 minutes read.

Delete N nodes after M nodes of a linked list

Delete N nodes after M nodes of a linked list In this problem, we have given a linked list and two integers M and N. We need to traverse the linked...

3 minutes read.

Understanding Data Processing

Introduction Data In our everyday lives, any task that we perform online is related to data. Millions of pieces of data are produced every second across the globe. Data production is largely...

4 minutes read.

Binary Tree vs Binary Search Tree: Data Structure

Difference Between Binary Tree and Binary Search Tree What is Binary Tree? A tree which each node can have utmost two children called binary tree. These children are referred as the ‘left...

3 minutes read.

What is the Use of Segment Trees in Data Structure?

Segment trees Segment trees are also called statistical trees in computer science. They are a type of tree data structure. Segment trees are used to store information regarding segments and intervals....

6 minutes read.

Strictly binary tree in Data Structures?

What is a strictly Binary Tree in Data Structures? There are various kinds of binary trees that we know exist in data structures, and they all have their purposes. In this...

4 minutes read.

Sorting Algorithms

Sorting: In the data structure, sorting is the process by which you arrange the data in a logical order. This logical order can also be an ascending order or a...

7 minutes read.

What Is Graph Data Structure

A graph is generally a set of vertices and edges or border that is mainly used to join these vertices. A graph is basically pictured as a cyclic tree in...

7 minutes read.