Write a C program to Delete a Tree

To delete a tree , we need to travel all node and delete node one by one .
Since before deleting the parent node we should delete its children nodes first So we use preorder traversal to visit each node and delete that node .

Code :

/*  This function traverses tree in post order to
    to delete each and every node of the tree */
void deleteTree(struct node* node)
{
    if (node == NULL) 
     return;
 
    /* first delete both subtrees */
    deleteTree(node->left);
    deleteTree(node->right);
 
    /* then delete the node */
    printf("\n Deleting node: %d", node->data);
    free(node);
}

Time & Space Complexities: Since this program is similar to traversal of tree, time and space complexities will be same as Tree traversal .

Leave a Reply

Your email address will not be published. Required fields are marked *

For Inserting code :
Paste your code in the comment form, select it and then click the language link

C | C++ | Java |

*