Code to count number of leaves of a tree? [closed]

I've just started learning C. Can anyone tell me whether my code is correct or not, if not what's the correct version? This is code for counting number of leaf nodes. Is this efficient one if this is correct?

void Count_leaf( Tree* head)
{       static leaf = 0;
leaf++;
else
}
}

• Code review belongs to codereview.se. – Yuval Filmus May 28 '17 at 15:53
• Coding questions are off-topic here. (My understanding is that CodeReview.SE is only for code that you already know to be correct, so it's probably not the site for this, either.) – D.W. May 28 '17 at 16:12
• Okay officers... – Mr. Sigma. May 28 '17 at 16:21

Using this recursive algorithm is indeed a correct way. But your code is wrong, and it could use some improvements.

First of all, you are using a pointer for head so you should use -> instead of . to access the left and right element.

Then, using a static variable is not the cleanest way to store the result. You could use the recursion and simply return the result, like so:

int Count_leaf(Tree* head)
{
return 1;
else
}


Finally, you should check if the tree is empty before starting any counting. You can add a simple condition at the start of your fonction to do that:

if(head == NULL)
return 0;


Here is the final program:

int Count_leaf(Tree* head)
{

• Thanks. What if I want to keep return type void only? Which data type I should use instead of static? – Mr. Sigma. May 28 '17 at 14:22