A recursive and a non-recursive program to delete an entire binary tree has already been discussed in the previous posts. In this post, deleting the entire binary tree using the delete keyword in C++ is discussed.
Declare a destructor function in the ‘BinaryTreeNode’ class which has been defined to create a tree node. Using ‘delete’ keyword on an object of a class deletes the entire binary tree., it’s destructor is called within the destructor. Use the ‘delete’ keyword for the children; so the destructors for the children will be called one by one, and the process will go on recursively until the entire binary tree is deleted. Consider the tree shown below, as soon as the destructor is called for the root i.e., ‘1’, it will call the destructors for ‘2’ and ‘3’, and 2 will then call the same for its left and right child with data ‘4’ and ‘5’ respectively. Eventually, the tree will be deleted in the order: 4->5->2->3->1 (Post-order)
Below is the C++ implementation of the above approach:
Deleting 4 Deleting 5 Deleting 2 Deleting 3 Deleting 1
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.