Data Structures Tutorial

Data Structures Tutorial Asymptotic Notation Structure and Union Array Data Structure Linked list Data Structure Type of Linked list Advantages and Disadvantages of linked list Queue Data Structure Implementation of Queue Stack Data Structure Implementation of Stack Sorting Insertion sort Quick sort Selection sort Heap sort Merge sort Bucket sort Count sort Radix sort Shell sort Tree Traversal of the binary tree Binary search tree Graph Spanning tree Linear Search Binary Search Hashing Collision Resolution Techniques

Misc Topic:

Priority Queue in Data Structure Deque in Data Structure Difference Between Linear And Non Linear Data Structures Queue Operations In Data Structure About Data Structures Data Structures Algorithms Types of Data Structures Big O Notations Introduction to Arrays Introduction to 1D-Arrays Operations on 1D-Arrays Introduction to 2D-Arrays Operations on 2D-Arrays Strings in Data Structures String Operations Application of 2D array Bubble Sort Insertion Sort Sorting Algorithms What is DFS Algorithm What Is Graph Data Structure What is the difference between Tree and Graph What is the difference between DFS and BFS Bucket Sort Dijkstra’s vs Bellman-Ford Algorithm Linear Queue Data Structure in C Stack Using Array Stack Using Linked List Recursion in Fibonacci Stack vs Array What is Skewed Binary Tree Primitive Data Structure in C Dynamic memory allocation of structure in C Application of Stack in Data Structures Binary Tree in Data Structures Heap Data Structure Recursion - Factorial and Fibonacci What is B tree what is B+ tree Huffman tree in Data Structures Insertion Sort vs Bubble Sort Adding one to the number represented an array of digits Bitwise Operators and their Important Tricks Blowfish algorithm Bubble Sort vs Selection Sort Hashing and its Applications Heap Sort vs Merge Sort Insertion Sort vs Selection Sort Merge Conflicts and ways to handle them Difference between Stack and Queue AVL tree in data structure c++ Bubble sort algorithm using Javascript Buffer overflow attack with examples Find out the area between two concentric circles Lowest common ancestor in a binary search tree Number of visible boxes putting one inside another Program to calculate the area of the circumcircle of an equilateral triangle Red-black Tree in Data Structures Strictly binary tree in Data Structures 2-3 Trees and Basic Operations on them Asynchronous advantage actor-critic (A3C) Algorithm Bubble Sort vs Heap Sort Digital Search Tree in Data Structures Minimum Spanning Tree Permutation Sort or Bogo Sort Quick Sort vs Merge Sort Boruvkas algorithm Bubble Sort vs Quick Sort Common Operations on various Data Structures Detect and Remove Loop in a Linked List How to Start Learning DSA Print kth least significant bit number Why is Binary Heap Preferred over BST for Priority Queue Bin Packing Problem Binary Tree Inorder Traversal Burning binary tree Equal Sum What is a Threaded Binary Tree? What is a full Binary Tree? Bubble Sort vs Merge Sort B+ Tree Program in Q language Deletion Operation from A B Tree Deletion Operation of the binary search tree in C++ language Does Overloading Work with Inheritance Balanced Binary Tree Binary tree deletion Binary tree insertion Cocktail Sort Comb Sort FIFO approach Operations of B Tree in C++ Language Recaman’s Sequence Tim Sort Understanding Data Processing Applications of trees in data structures Binary Tree Implementation Using Arrays Convert a Binary Tree into a Binary Search Tree Create a binary search tree Horizontal and Vertical Scaling Invert binary tree LCA of binary tree Linked List Representation of Binary Tree Optimal binary search tree in DSA Serialize and Deserialize a Binary Tree Tree terminology in Data structures Vertical Order Traversal of Binary Tree What is a Height-Balanced Tree in Data Structure Convert binary tree to a doubly linked list Fundamental of Algorithms Introduction and Implementation of Bloom Filter Optimal binary search tree using dynamic programming Right side view of binary tree Symmetric binary tree Trim a binary search tree What is a Sparse Matrix in Data Structure What is a Tree in Terms of a Graph What is the Use of Segment Trees in Data Structure What Should We Learn First Trees or Graphs in Data Structures All About Minimum Cost Spanning Trees in Data Structure Convert Binary Tree into a Threaded Binary Tree Difference between Structured and Object-Oriented Analysis FLEX (Fast Lexical Analyzer Generator) Object-Oriented Analysis and Design Sum of Nodes in a Binary Tree What are the types of Trees in Data Structure What is a 2-3 Tree in Data Structure What is a Spanning Tree in Data Structure What is an AVL Tree in Data Structure Given a Binary Tree, Check if it's balanced

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



ADVERTISEMENT
ADVERTISEMENT