To delete a tree, we need to traverse each node of the tree and delete them one by one. This way, we can delete each node of the tree one by one, making it empty. To do this we need to use a method that traverses the tree from the bottom up so that we can remove lower nodes first and then their parents to avoid additional complexity. Based on our needs, postorder traversal is the most suitable and works efficiently to make our program optimal.
The post-order traversal of the following tree is -
2-6-4-12-17-15
The post-order traversal cell technology works as follows:
Check the left child node→Check the root node→Check the right child Node
#include<stdio.h> #include<stdlib.h> 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; return(node); } void nodedel(struct node* node) { if (node == NULL) return; nodedel(node->left); nodedel(node->right); printf("</p><p> 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("</p><p> 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
The above is the detailed content of Write a C programming program to delete a tree. For more information, please follow other related articles on the PHP Chinese website!