

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 -
2-6-4-12-17-15
The postorder travel cell technique works in by the following way -
checks for the left childnode → check for the rootnode → chekcs the right childnode
Example
#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; }
Output
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
- Related Questions & Answers
- Write a function to delete a Linked List in C++ Programming
- Write a program to Calculate Size of a tree - Recursion in C++
- Write a function to delete a Linked List in C++
- Write a C Program to delete the duplicate numbers in an array
- Deleting a binary tree using the delete keyword in C++ program
- Write a program that produces different results in C and C++ programming
- C program to delete a file
- Write a Program to Find the Maximum Depth or Height of a Tree in C++
- Delete Tree Nodes in C++
- Deleting a binary tree using the delete keyword in C++?
- Write a URL in a C++ program
- Write a C program to reverse array
- Write program to shutdown a system in C/C++
- Program to delete all leaves with even values from a binary tree in Python
- Binary Search Tree - Delete Operation in C++
Advertisements