Counting no of nodes in tree

int countNodes(TreeNode* temp) {

   if(temp==NULL)
       return 0;
   if(temp->right!=NULL)
       return 1+countNodes(temp->right);
    if(temp->left!=NULL)
        return 1+countNodes(temp->left);
   return 0;

    
}

i wrote this function to find to count no of node in tree
but im getting different expected output.

@star.gmmn hi see you have done a mistake that when u do in base case that it node is empty return 0 so do not write that if left or right null !=0
int countNodes(TreeNode* temp) {
if(temp==NULL)
return 0;
return countNodes(temp->left)+countNodes(temp->right)+1;
}

just do this

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

i guess my code returns the no of node at level 1 right…

may be that @star.gmmn yes

@star.gmmn
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.