Your code looks correct to me, but just a little clumsy. So it should actually do the right thing. The bug must be in another part of the code. Why don't you improve your question by appending the code that calls your function and we take a look at that.
What I find clumsy about your code is mostly the naming. I would expect a function "IsLeaf" to return a bool which is true if this is a leaf node. In your case I would name the function:
CountLeafNodes
.
You have named the first and only argument of your function
root
. But in fact, you intend to call the function on any node, not just the root node of the tree. So why don't you name it then
pNode
? And as you are not going to return a value via this argument, I would transfer it by value and not by reference. So would bring us to:
int Tree::CountLeafNodes (node* pNode)
Now things start to fall in place. The last little modification I would suggest is to move this entire code into your node class. In your code you are accessing the members of class node in many locations and that is a sure sign that your function sits in the wrong class. If you make that a member function of node, things look even easier:
int node::CountLeafNodes ()
{
if (left==0 && middle==0 && right==0)
return 1;
int count = 0;
if (left)
count += left->CountLeafNode();
if (middle)
count += middle->CountLeafNode();
if (right)
count += right->CountLeafNode();
return count;
}
Looks a lot easier to read, doesn't it?