adplus-dvertising

C program to count number of leaf nodes in a Tree

frame-decoration

C program to count number of leaf nodes in a Tree

Problem Description

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
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
                 
  /*
 C Program to Count Number of Leaf Nodes in a Tree
 */
 
#include <stdio.h>
#include <stdlib.h>
 
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