Given a binary tree, write an efficient algorithm to delete the entire binary tree. The algorithm should deallocate every single node present in the tree, not just change the root node’s reference to null.

Recursive Solution

The idea is to traverse the tree in a postorder fashion and delete the left and right subtree of a node before deleting the node itself. Note that we cannot traverse a tree in preorder or inorder fashion as we can’t delete a parent before deleting its children.

Following is the C++ program that demonstrates it:

C++


Download  Run Code

The time complexity of the above recursive solution is O(n), where n is the total number of nodes in the binary tree. The auxiliary space required by the program is O(h) for the call stack, where h is the height of the tree.

Iterative Solution

In the iterative version, perform a level order traversal on the tree. The idea is to delete each node in the queue, one by one, after enqueuing their children. Note that the parent is deleted before deleting its children as we are enqueuing them, and they will be processed and deleted afterward.

This is demonstrated below in C++:

C++


Download  Run Code

The time complexity of the above iterative solution is O(n), where n is the total number of nodes in the binary tree. The auxiliary space required by the program is O(n) for the queue data structure.