Deleting a binary tree using the delete keyword in C++ program


In this tutorial, we are going to learn how to delete a binary tree using the delete keyword.

We are going to use a destructor member function to delete the binary. The destructor member function is invoked automatically when the object goes out of the scope or it is destroyed by calling delete.

The destructor member function has the name as a class with tilde (~) before it.

Let's see the steps to solve the problem.

  • Write a class called Node.

  • Write a constructor function that accepts data for the node.

  • Write a destructor function.

    • Delete the left node.

    • Delete the right node.

    • Print the current node data.

  • Initialize the binary tree with dummy data.

  • Delete the binary tress using the delete root statement.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Node {
   public:
   int data;
   Node* left;
   Node* right;
   // constructor
   Node(int data) {
      this->data = data;
      this->left = NULL;
      this->right = NULL;
   }
   // destructor
   ~Node() {
      // deleting the left and right pointers
      delete left;
      delete right;
      // printing node data
      cout << "Deleted node with data " << this->data << endl;
   }
};
int main() {
   Node* root = new Node(1);
   root->left = new Node(2);
   root->right = new Node(3);
   root->left->left = new Node(4);
   root->left->right = new Node(5);
   root->right->left = new Node(6);
   root->right->right = new Node(7);
   // deleting the entire tree using destructure function
   delete root;
   return 0;
}

Output

If you execute the above program, then you will get the following result.

Deleted node with data 4
Deleted node with data 5
Deleted node with data 2
Deleted node with data 6
Deleted node with data 7
Deleted node with data 3
Deleted node with data 1

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 27-Jan-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements