Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Write a program to Delete a Tree in C programming
To delete a tree in C programming, we need to traverse each node and free the memory allocated to them. The key is to delete nodes in the correct order − children must be deleted before their parents to avoid memory leaks and dangling pointers. Post-order traversal is ideal for this operation as it visits children before the parent node.
Syntax
void deleteTree(struct node* root) {
if (root == NULL) return;
deleteTree(root->left);
deleteTree(root->right);
free(root);
}
How Post-order Traversal Works for Deletion
Post-order traversal follows this pattern:
- Visit left subtree
- Visit right subtree
- Visit root node
This ensures that all children are processed before the parent node, making it safe to delete the parent without losing references to its children.
Example: Complete Tree Deletion Program
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* left;
struct node* right;
};
struct node* createNode(int data) {
struct node* newNode = (struct node*)malloc(sizeof(struct node));
if (newNode == NULL) {
printf("Memory allocation failed<br>");
return NULL;
}
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
void deleteTree(struct node* root) {
if (root == NULL) return;
/* Delete left subtree first */
deleteTree(root->left);
/* Delete right subtree */
deleteTree(root->right);
/* Delete current node */
printf("Deleting node with value: %d<br>", root->data);
free(root);
}
int main() {
/* Create the tree */
struct node *root = createNode(9);
root->left = createNode(4);
root->right = createNode(15);
root->left->left = createNode(2);
root->left->right = createNode(6);
root->right->left = createNode(12);
root->right->right = createNode(17);
printf("Deleting the entire tree:<br>");
deleteTree(root);
root = NULL; /* Prevent dangling pointer */
printf("Tree successfully deleted!<br>");
return 0;
}
Deleting the entire tree: Deleting node with value: 2 Deleting node with value: 6 Deleting node with value: 4 Deleting node with value: 12 Deleting node with value: 17 Deleting node with value: 15 Deleting node with value: 9 Tree successfully deleted!
Key Points
- Post-order traversal ensures children are deleted before parents
- Always check for
NULLpointers to avoid segmentation faults - Set root to
NULLafter deletion to prevent dangling pointer access - The time complexity is O(n) where n is the number of nodes
- Space complexity is O(h) where h is the height of the tree due to recursion stack
Conclusion
Deleting a binary tree requires careful memory management using post-order traversal. This approach ensures all child nodes are freed before their parents, preventing memory leaks and maintaining program stability.
