belongs to collection: C programs - Trees
This C Program counts the number of leaf nodes in a Tree.
C program to count number of leaf nodes in a Tree - Source code
struct bt_node { int value; struct bt_node * l; struct bt_node * r; }; typedef struct bt_node bt; bt *root; bt *new, *list; int count = 0; bt * create_node(); void display(bt *); void construct_tree(); void count_leaf(bt *); void main() { construct_tree(); display(root); count_leaf(root); printf("\n leaf nodes are : %d",count); } /* To create a empty node */ bt * create_node() { new = (bt *)malloc(sizeof(bt)); new->l = NULL; new->r = NULL; } /* To construct a tree */ void construct_tree() { root = create_node(); root->value = 100; root->l = create_node(); root->l->value = 50; root->r = create_node(); root->r->value = 55; root->l->l = create_node(); root->l->l->value = 70; root->l->r = create_node(); root->l->r->value = 80; root->l->r->r = create_node(); root->l->r->r->value = 60; root->l->l->l = create_node(); root->l->l->l->value = 10; root->l->l->r = create_node(); root->l->l->r->value = 40; } /* To display the elements in a tree using inorder traversal */ void display(bt * list) { if (list == NULL) { return; } display(list->l); printf("->%d", list->value); display(list->r); } /* To count the number of leaf nodes */ void count_leaf(bt * list) { if (list == NULL) { return; } if (list->l == NULL && list->r == NULL) { count++; } count_leaf(list->l); count_leaf(list->r); }
Program Output
->10->70->40->50->80->60->100->55 leaf nodes are : 4
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
C program to count number of leaf nodes in a Tree - Source code
Program Output
need an explanation for this answer? contact us directly to get an explanation for this answer