C Program to Count Leaf Nodes in a Tree

This is a C Program to calculate number of leaf nodes in a tree.

Problem Description

We are given a tree, and we have to write a C program to find the total number of leaf nodes present in a tree using recursion. We have to create a recursive function which takes in root of the tree as input and returns count of number of leaf nodes present in a tree.

Expected Input and Output

Case 1.Tree having same weight on both the sides of root node (A Balanced Tree). For Example:

If the input tree is      
                    25
                  /    \
                 27     19
                / \     / \
              17  91   13 55
then number of leaf nodes in this tree will be 4

Case 2. Tree having only right children at every level (Right Skewed Tree). A right skewed tree is one in which all the nodes just have a right child at all the levels. For example:

 If the input tree is      
                    1
                     \
                      2
                       \
                        3
                         \
                          4
                           \
                            5 
then number of leaf nodes in this tree will be 1

Case 3. Tree having just one node

advertisement
advertisement
If the input tree is
                           15                                         
then number of leaf nodes in this tree will be 1
Problem Solution

We can easily find the number of leaf nodes present in any tree using recursion. A leaf node is a node whose left and right child are NULL. We just need to check this single condition to determine whether the node is a leaf node or a non leaf (internal) node.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
Program/Source Code

Here is source code of the C Program to count the total number of leaf nodes present in a given tree. The program is successfully compiled and tested using Codeblocks gnu/GCC compiler on windows 10. The program output is also shown below.

  1. /* C Program to find the number of leaf nodes in a Tree */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. struct node
  6. {
  7.     int info;
  8.     struct node* left, *right;
  9.  
  10. };
  11.  
  12. /*
  13.  * Function to create new nodes
  14.  */
  15.  
  16. struct node* createnode(int key)
  17. {
  18.     struct node* newnode = (struct node*)malloc(sizeof(struct node));
  19.     newnode->info = key;
  20.     newnode->left = NULL;
  21.     newnode->right = NULL;
  22.  
  23.     return(newnode);
  24. }
  25.  
  26. /* 
  27.  * Function to count number of leaf nodes
  28.  */
  29.  
  30. int count = 0;
  31. int leafnodes(struct node* newnode)
  32. {
  33.  
  34.     if(newnode != NULL)
  35.     {
  36.         leafnodes(newnode->left);
  37.         if((newnode->left == NULL) && (newnode->right == NULL))
  38.         {
  39.             count++;
  40.         }
  41.         leafnodes(newnode->right);
  42.     }
  43.     return count;
  44.  
  45. }
  46.  
  47. /*
  48.  * Main Function
  49.  */
  50.  
  51. int main()
  52. {
  53.    /* Creating first Tree.*/
  54.  
  55.     struct node *newnode = createnode(25);
  56.     newnode->left = createnode(27);
  57.     newnode->right = createnode(19);
  58.     newnode->left->left = createnode(17);
  59.     newnode->left->right = createnode(91);
  60.     newnode->right->left = createnode(13);
  61.     newnode->right->right = createnode(55);
  62.  
  63.     /* Sample Tree 1- Balanced Tree
  64.  
  65.  
  66.                     25
  67.                   /    \
  68.                  27     19
  69.                 / \     / \
  70.               17  91   13 55
  71.  
  72.     */
  73.     printf("Number of leaf nodes in first Tree are\t%d\n",leafnodes(newnode));
  74.     count = 0;
  75.  
  76.     struct node *node = createnode(1);
  77.     node->right = createnode(2);
  78.     node->right->right = createnode(3);
  79.     node->right->right->right = createnode(4);
  80.     node->right->right->right->right = createnode(5);
  81.  
  82.     /* Sample Tree 2-   Right Skewed Tree (Unbalanced).
  83.  
  84.                     1
  85.                      \
  86.                       2
  87.                        \
  88.                         3
  89.                          \
  90.                           4
  91.                            \
  92.                             5
  93.     */
  94.  
  95.     printf("\nNumber of leaf nodes in second tree are\t%d\n",leafnodes(node));
  96.     count = 0;
  97.  
  98.     /*Creating third Tree. */
  99.  
  100.     struct node *root = createnode(15);
  101.  
  102.     /* Sample Tree 3-  Tree having just one root node.
  103.  
  104.                    15
  105.     */
  106.  
  107.     printf("\nNumber of leaf nodes in third tree are\t%d",leafnodes(root));
  108.  
  109.     return 0;
  110. }
Program Explanation

1. In this program we have used recursion to find the total number of leaf nodes present in a tree. A Leaf Node is one whose left and right child are NULL.
2. We have created a function called leafnodes() which takes in root of the tree as a parameter and returns the total number of leaf nodes it has.
3. The basic idea is to traverse the tree using any traversal so as to visit each and every node and check the condition for leaf node for each node, that is what we have done in leafnodes() function.
4. In the leafnodes() function we have used the inorder traversal, by first traversing the left subtree, then instead of printing the root->data as a second step of inorder traversal, we have checked the leaf node condition and then at last we have traversed the right subtree by passing root->right as a parameter.

advertisement
Runtime Test Cases
Number of leaf nodes in first Tree are  4
 
Number of leaf nodes in second tree are 1
 
Number of leaf nodes in third tree are  1

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

advertisement
If you wish to look at programming examples on all topics, go to C Programming Examples.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.