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

C++Server Side ProgrammingProgramming

Let us first define our binary tree using a class containing int data, btree_node * rightChild, btree_node * leftChild. The leftChild and rightChild are pointers to btree_node. All the members in our class are public.

class btree_node {
   public:
      int data;
      btree_node* leftChild;
      btree_node* rightChild;

For creating a new node we have the constructor function that takes the int value as parameter to assign it to the newly created node value. The leftChild and rightChild are set to null.

btree_node(int data){
   this->data = data;
   this->leftChild = NULL;
   this-> = NULL;
}

The class deconstructor deletes the left and right child of the binary tree using the delete keyword when being invoked.

~btree_node(){
   delete leftChild;
   delete rightChild;
   cout << this->data << "is being deleted"<<endl;
}

To trigger the deletion of the tree we call the delete on the root node as its left and right subtree will be deleted along.

delete root;

Example

Let us see the following implementation for deleting binary tree using the delete keyword −

 Live Demo

#include <iostream>
using namespace std;
class btree_node {
   public:
   int data;
   btree_node* leftChild;
   btree_node* rightChild;
   btree_node(int data){
      this->data = data;
      this->leftChild = NULL;
      this->rightChild = NULL;
   }
   ~btree_node(){
      delete leftChild;
      delete rightChild;
      cout << this->data << " is being deleted"<<endl;
   }
};
int main(){
   btree_node* root = new btree_node(2);
   btree_node* node1 = new btree_node(4);
   btree_node* node2 = new btree_node(6);
   btree_node* node3 = new btree_node(8);
   btree_node* node4 = new btree_node(10);
   root->leftChild = node1;
   root->rightChild = node2;
   node1->leftChild = node3;
   node1->rightChild = node4;
   delete root;
   return 0;
}

Output

The above code will produce the following output −

8 is being deleted
10 is being deleted
4 is being deleted
6 is being deleted
2 is being deleted
raja
Published on 16-Jan-2021 12:00:28
Advertisements