In: Computer Science
Write a solution to return the count of the number of nodes in a binary tree. Your method will be passed one parameter, a copy of a pointer to the root node of the tree (Node *) and will return an int that is the count of nodes. If the tree is empty, return 0 (this is the recursive base case).
ANS:
//The number of nodes in Binary tree will be the sum of number of nodes of left subtree plus the number of nodes in //right subtree
int
count_recursive(
Node
*root)
{
int
count = 0;
if
(root->left == NULL && root->right ==
NULL)
{
count
= 0; // if empty it will return 0
}
else
{
if
(root->left != NULL)
{
count
+=
count_recursive(root->left); //Recursive
Call for left subtree
}
if
(root->right != NULL)
{
count
+=
count_recursive(root->right);
//Recursive call for right subtree
}
}
return
count;
}
Comment down
for any queries
Please give a thumbs up if you are satisfied with answer
:)