Description: Given a tree, we have to delete all nodes of the tree.

 
If video does not load, Click here
 
Algorithm and implementation:

 

We need to traverse all nodes in the tree and delete them one-by-one such that we delete children before deleting the parent so that we’re able to access the parent. If however, we delete parent first, we can’t access children anymore.

 

Among,

-Inorder

-Preorder

-Postorder

We traverse using postorder traversal and delete nodes.

 

/*The following function deletes all nodes of the tree.*/

void delete(struct node* node)

{

   if (node == NULL) return;

 

   delete(node->left);/*delete left subtree*/

   delete(node->right); /*delete right subtree*/

  

   /*now delete current node*/

   free(node);

}

 

Time Complexity:

 

O(n), where 'n' is the number of nodes in the tree.

Go to top