C Program to Count the Number of Nodes in Binary Tree

This is a C Program for counting the number of nodes present in a tree using recursion.

Problem Description

Here in this problem we will be finding the total number of nodes present in a given tree using C Language.

Expected Input and Output

Case 1. Balanced Tree:When the weight is equal on both the sides of root.

                    25
                  /    \  
                 27     19   
                / \     / \ 
              17  91   13 55

Output: 7

Case 2. Right Skewed Tree:When the nodes at every level just have a right child.

                    1   
                     \
                      2    
                       \    
                        3 
                         \
                          4
                           \
                            5

Output: 5

advertisement
advertisement

Case 3. Tree having just one node

                    15

Output: 1

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
Problem Solution

1. In order to count the number of nodes in a tree we just need to traverse the whole tree once. We can use any of the traversal techniques to count the number of nodes.
2. We have to take a count variable and initialize it with 0 and for each node which we traverse we just have to increase the value of count.

Program/Source Code

Here is source code of the C Program for counting the number of nodes present in a 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 for counting the number of nodes in a Tree */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. struct node
  5. {
  6.     int info;
  7.     struct node *left, *right;
  8. };
  9. struct node *createnode(int key)
  10. {
  11.     struct node *newnode = (struct node*)malloc(sizeof(struct node));
  12.     newnode->info = key;
  13.     newnode->left = NULL;
  14.     newnode->right = NULL;
  15.     return(newnode);
  16. }
  17. static int count = 0;
  18. int countnodes(struct node *root)
  19. {
  20.     if(root != NULL)
  21.     {
  22.         countnodes(root->left);
  23.         count++;
  24.         countnodes(root->right);
  25.     }
  26.     return count;
  27. }
  28. /*
  29.  * Main Function
  30.  */
  31. int main()
  32. {
  33.     /* Creating first Tree. */
  34.     struct node *newnode = createnode(25);
  35.     newnode->left = createnode(27);
  36.     newnode->right = createnode(19);
  37.     newnode->left->left = createnode(17);
  38.     newnode->left->right = createnode(91);
  39.     newnode->right->left = createnode(13);
  40.     newnode->right->right = createnode(55);
  41.     /* Sample Tree 1:
  42.      *                25
  43.      *             /    \
  44.      *            27     19
  45.      *           / \     / \
  46.      *         17  91   13 55
  47.      */
  48.     printf("Number of nodes in tree 1 = %d ",countnodes(newnode));
  49.     printf("\n");
  50.     count = 0;
  51.  
  52.     /* Creating second Tree. */
  53.     struct node *node = createnode(1);
  54.     node->right = createnode(2);
  55.     node->right->right = createnode(3);
  56.     node->right->right->right = createnode(4);
  57.     node->right->right->right->right = createnode(5);
  58.     /* Sample Tree 2:   Right Skewed Tree (Unbalanced).
  59.      *               1
  60.      *                \
  61.      *                 2
  62.      *                  \
  63.      *                   3
  64.      *                    \
  65.      *                     4
  66.      *                      \
  67.      *                       5
  68.      */
  69.     printf("Number of nodes in tree 2 = %d ",countnodes(node));
  70.     printf("\n");
  71.     count = 0;
  72.  
  73.     /* Creating third Tree. */
  74.     struct node *root = createnode(15);
  75.     /* Sample Tree 3- Tree having just one root node.
  76.      *              15
  77.      */
  78.     printf("Number of nodes in tree 3 = %d",countnodes(root));
  79.     return 0;
  80. }
Program Explanation

Program contains two important functions.

advertisement

1. createnode(key);
This function helps to create a new node by allocating it a memory dynamically. It has just one parameter which is “key” which assigns value to the node thereby creating a fresh node having left and right child as “NULL”.

2. countnodes(struct node *root);
In this function we have traversed the left and right subtree and increased the count variable which counts the total number of nodes present in the left and the right subtree. The traversal technique which we have used here is inorder traversal of a tree, by first passing root->left then instead of printing the root->data as a next step of inorder traversal we increase the count variable and then we have passed the root->right to traverse the right subtree and count the total number of nodes present in the right subtree.

Runtime Test Cases
Number of nodes in tree 1 = 7
Number of nodes in tree 2 = 5
Number of nodes in tree 3 = 1

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement

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

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

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.