If you want to Delete a Tree in C programming language, then use the following c program. To delete a tree we must traverse all the nodes of the tree and delete them one by one.
Below is the post-order for the tree:
1 | 2-6-4-12-17-15 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | #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("\n 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("\n Tree deleted "); return 0; } |
Program Output
1 2 3 4 5 6 | 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 |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.