Question: How do you count the nodes of a binary tree?
Solution :
Like almost all functions in a binary tree, this algorithm also needs a recursive function.
- The no. of nodes of a binary tree = 0 if the node is NULL
- = 1 +
- no. of nodes in left sub-tree+
- no.of nodes in right sub-tree.
- Calculate recursively for all sub-trees.
Here is C++ code for the same.
int bintree::count()
{
return count_leaf_nodes(root);
}
int bintree::count_nodes(node * nd)
{
if(nd==NULL)
return 0;
if(nd->left ==NULL && nd->right==NULL)
return 1;
return 1+count_nodes(nd->left)+count_nodes(nd->right);
}
Comments
Post a Comment