Write a solution to return the count of the number of nodes in a binary tree....

Free

60.1K

Verified Solution

Question

Programming

Write a solution to return the count of the number of nodes in abinary tree. Your method will be passed one parameter, a copy of apointer to the root node of the tree (Node *) and will return anint that is the count of nodes. If the tree is empty, return 0(this is the recursive base case).

Answer & Explanation Solved by verified expert
3.6 Ratings (583 Votes)

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 :)


Get Answers to Unlimited Questions

Join us to gain access to millions of questions and expert answers. Enjoy exclusive benefits tailored just for you!

Membership Benefits:
  • Unlimited Question Access with detailed Answers
  • Zin AI - 3 Million Words
  • 10 Dall-E 3 Images
  • 20 Plot Generations
  • Conversation with Dialogue Memory
  • No Ads, Ever!
  • Access to Our Best AI Platform: Flex AI - Your personal assistant for all your inquiries!
Become a Member

Other questions asked by students