This is another recursive algorithm. If we are a leaf node, we return 1, and if not, we recurse into the left and right subtrees and return the sum of the leaves in them.

unsigned int binarytree_count_leaves_recursive(const btnode *root)
{
unsigned int count = 0;
if (root->left == NULL && root->right == NULL) {
count = 1;
}
else {
if (root->left != NULL) {
count += binarytree_count_leaves_recursive(root->left);
}
if (root->right != NULL) {
count += binarytree_count_leaves_recursive(root->right);
}
}
return count;
}
unsigned int binarytree_count_leaves(const binarytree *tree)
{
unsigned int count = 0;
if (tree->root != NULL) {
count = binarytree_count_leaves_recursive(tree->root);
}
return count;
}

## Related