Write a C Program to count leaf nodes in a binary tree

A node is a leaf node if both left and right child nodes of it are NULL.

Algorithm :

1) If node is NULL then return 0.
2) Else If left and right child nodes are NULL return 1.
3) Else recursively calculate leaf count of the tree using below formula.
    Leaf count of a tree = Leaf count of left subtree +
                                 Leaf count of right subtree

Code :

/* Function to get the count of leaf nodes in a binary tree*/
int getLeafCount(struct node* node)
{
  if(node == NULL)
    return 0;
  if(node->left == NULL && node->right==NULL)
    return 1;
  else
    return getLeafCount(node->left) + getLeafCount(node->right);
}

Time and Space Complexities: Above program is similar to traversal of tree, time and space complexities will be same as Tree traversal .

Leave a Reply

Your email address will not be published. Required fields are marked *

For Inserting code :
Paste your code in the comment form, select it and then click the language link

C | C++ | Java |

*