Home > Backend Development > C++ > body text

Write a C programming program to delete a tree

WBOY
Release: 2023-08-26 14:45:05
forward
1080 people have browsed it

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
Copy after login

The post-order traversal cell technology works as follows:

Check the left child node→Check the root node→Check the right child Node

Write a C programming program to delete a tree

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("</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;
}
Copy after login

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
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!