0
$\begingroup$

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;
            if(head.left==NULL && head.right==NULL)
            leaf++;
            else
            {     Count_leaf(head.left);
                  Count_leaf(head.right);
            }
    } 
$\endgroup$
  • $\begingroup$ Code review belongs to codereview.se. $\endgroup$ – Yuval Filmus May 28 '17 at 15:53
  • $\begingroup$ 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.) $\endgroup$ – D.W. May 28 '17 at 16:12
  • $\begingroup$ Okay officers... $\endgroup$ – Mr. Sigma. May 28 '17 at 16:21
2
$\begingroup$

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)
{
    if(head->left == NULL && head->right == NULL)
        return 1;
    else
        return Count_leaf(head->left) + Count_leaf(head->right);
} 

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)
{
    if(head == NULL)
        return 0;

    if(head->left == NULL && head->right == NULL)
        return 1;
    else
        return Count_leaf(head->left) + Count_leaf(head->right);
} 
$\endgroup$
  • $\begingroup$ Thanks. What if I want to keep return type void only? Which data type I should use instead of static? $\endgroup$ – Mr. Sigma. May 28 '17 at 14:22
  • 1
    $\begingroup$ @RohitSinghRathore The data type is alright, but I just pointed out it was not a clean way of using it when you have another easy solution (the one I used in my answer). You can also use a global variable if your project/file is relatively small. $\endgroup$ – haltode May 28 '17 at 14:25
  • $\begingroup$ @RohitSinghRathore You're welcome, don't forget to mark your problem as solved if you don't have any other question. $\endgroup$ – haltode May 28 '17 at 14:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.