does anybody know the code for finding the number of nodes in a search tree
does anybody know the code for finding the number of nodes in a search tree
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:
So it's good.Code:* * * * * * *
Prelude
My best code is written with the delete key.
Haven't tested it, looks correct though.Code:int NodeCount( Node* pNode ) { if( pNode != NULL ) return 1 + NodeCount( pNode->pLeftChild ) + NodeCount( pNode->pRightChild ); else return 0; }
"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens