To count the number of nodes in a given binary search tree, the tree is required to be traversed recursively until a leaf node is encountered. When a leaf node is encountered, a count of 1 is returned to its previous activation (which is an activation for its parent), which takes the count returned from both the children’s activation, adds 1 to it, and returns this value to the activation of its parent. This way, when the activation for the root of the binary search tree returns, it returns the count of the total number of the nodes in the binary tree.

int count(struct tnode *p)
{
if( p == NULL)
return(0);
else
if( p->lchild == NULL && p->rchild == NULL)
return(1);
else
return(1 + (count(p->lchild) + count(p->rchild)));
}

Try this on the binary search tree give below. Find out the number of nodes in the binary search tree using the program above.

Find out how do you get the height of the binary search tree?

### Like this:

Like Loading...

*Related*