Write a program to Delete a Tree in C programming

To delete a tree we need to traverse each node of the tree and then delete each of them. this one by one delete every node of the tree and makes it empty. For this, we need to use a method that traverses the tree from bottom to up so that we can delete the lower notes first and then their parents so that no extra complexities arise. Based on the condition that we need, The postorder traversal will be the best suited And works efficiently so that our program will be optimum.

The post-order for the following tree is -


The postorder travel cell technique works in by the following way -

checks for the left childnode → check for the rootnode → chekcs the right childnode


struct node {
   int data;
   struct node* left;
   struct node* right;
struct node* addnode(int data) {
   struct node* node = (struct node*)
      malloc(sizeof(struct node));
   node->data = data;
   node->left = NULL;
   node->right = NULL;
void nodedel(struct node* node) {
   if (node == NULL) return;
Node deleted, value is %d", node->data);    free(node); } int main() {    struct node *root = addnode(9);    root->left = addnode(4);    root->right = addnode(15);    root->left->left = addnode(2);    root->left->right = addnode(6);    root->right->left = addnode(12);    root->right->right = addnode(17);    nodedel(root);    root = NULL;    printf("
Tree deleted ");    return 0; }


Node deleted, value is 4
Node deleted, value is 12
Node deleted, value is 17
Node deleted, value is 15
Node deleted, value is 9
Tree deleted

Updated on: 09-Aug-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started