does anybody know the code for finding the number of nodes in a search tree

Printable View

- 04-23-2002Unregisterednumber of nodes in tree
does anybody know the code for finding the number of nodes in a search tree

- 04-23-2002Prelude
The easiest way is to traverse the tree and count them. But if the tree is balanced you might want to try something like 2^n+1 - 1.

If the height of the tree is 2 then

2^n+1 - 1 = 2^3 - 1 = 7

The tree would look like this:

Code:`*`

* *

* * * *

Prelude - 04-24-2002hk_mp5kpdwCode:
`int NodeCount( Node* pNode )`

{

if( pNode != NULL )

return 1 + NodeCount( pNode->pLeftChild ) + NodeCount( pNode->pRightChild );

else return 0;

}