How to count the total number of nodes in binary tree
I would rather do it by returning the sum in each recursive call without using the local variable.
int count(struct node *root){
if(root == NULL){
return 0;
}
else{
return 1 + count(root->left) + count(root->right);
}
}
You declare c
but not initialize nowhere and also not used in anywhere.
Then you print the value of c
, which gives you garbage value.
You can fix your count(node *tree)
function as
int count(node *tree)
{
int c = 1; //Node itself should be counted
if (tree ==NULL)
return 0;
else
{
c += count(tree->left);
c += count(tree->right);
return c;
}
}
add in main
int main()
{
.............
.............
c = count(root); //number of node assign to c
printf("Number of node %d \n",c);
}