### Counting Nodes of Binary Tree

Hello,

I am trying to count every node of a binary tree internally (not passing in the root), all my attemps have ended in memory access violation or an inaccurate count (4 or 5) when it should be 10.

This is what I have tried

And yes I am NOT suppose to pass in the root.

 ``12345678910`` `````` int CountChildren() { if ( !Left() && !Right()) return 1; if ( Left() ) return Left()->CountChildren() +1; if ( Right() ) return Right()->CountChildren() +1; } ``````

or

 ``12345678910`` `````` int CountChildren() { if(!Left() && !Right()) return 1; else return Left()->CountChildren()) + Right()->CountChildren() + 1; } ``````

Thank you
Last edited on
try the following code

 ``1234`` `````` int CountChildren() { return ( Left() ? Left()->CountChildren() : 0 ) + ( Right() ? Right()->CountChildren() : 0 ) + 1; } ``````
Wow, That worked. So simple, one line and you solved it. Thank you so much!

I am so use to passing in a root node that I was just stuck
I am writing your statement out as an if statement so I can understand it better, Would you mind converting it for me so I do not mess it up? I believe it reads like

if Left() then Left()->CoutChildren() else 0

+

Right()....

+ 1
It is equivalent to the following logic

 ``123456`` ``````int count = 1; if ( Left() ) count += Left()->CoutChildren(); if ( Right() ) count += Right()->CoutChildren(); return count;``````

You described the logic correctly.
Last edited on
I see, much cleaner using the ternary operators such as your initial solution. Thank you so much, this was giving me a headache, and in case you were wondering Im not lurking for HW answers, I am actually trying to learn this stuff better :)
It would be more cleaner to rewrite the function the following way

 ``12345`` ``````int CountChildren() const { return ( 1 + ( Left() ? Left()->CountChildren() : 0 ) + ( Right() ? Right()->CountChildren() : 0 ) ); } ``````

Last edited on
Topic archived. No new replies allowed.