this is the code for counting no of node. and im my code i am getting count of node wrong (getting no of node+1), please tell me why i am getting wrong output and how to solve it.
Getting wrong output
Your recursive relation was not correct.
Check now
can you please tell me wrong in my recursive relation
you are increasing the count when you reach at null
which will not give you correct ans
correct way to do this is
int count_no_of_nodes(node*root)
{
if(root==NULL)
return 0;
int cnt=0;
cnt+=count_no_of_nodes(root->right);
cnt+=count_no_of_nodes(root->left);
return cnt+1;
}
modified code
can you please explain how the function works in call stack
we start from root node and recursively call on left and right
when we reach at NULL we return 0 means no of nodes in NULL subtree is 0
similarly in backtrack we return the count of each subtree
at each node we take ans form left and right
and then add them and return the count of current subtree
int count_no_of_nodes(node*root) { if(root==NULL) return 0; count_no_of_nodes(root->left); count_no_of_nodes(root->right); return cnt++; }
can we right in this way. it is showing wrong ans
i did not understand it due to very poor indentation
please send the link of code