How to count number of nodes in a Binary Search Tree?


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?

About these ads
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: