- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write a program to Calculate Size of a tree - Recursion in C++
In this problem, we are given a tree and our task is to create a program to calculate the size of the tree using recursion.
The size of a tree is the total number of nodes present in the tree.
Let’s take an example to understand the problem,
The size of the above tree is 5.
To find the size of the tree, we will have to add the size of left subtree and right subtree and then increment it by 1. The recursive function will be called for both left and right subtrees of the tree. And if no subtree is found return 0.
Above example solved using this method
For finding the size of the tree,
size(3) = size(5) + size(7) + 1
size(3) = (size(1) + size(9) + 1) + 1 + 1
size(3) = (1 + 1 + 1) + 1 + 1
size(3) = 5
Program to illustrate the working of our solution,
Example
#include <iostream> using namespace std; class node { public: int data; node* left; node* right; }; node* insertNode(int data) { node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return(Node); } int findSize(node* node) { if (node == NULL) return 0; else return(findSize(node->left) + 1 + findSize(node->right)); } int main() { node *root = insertNode(6); root->left = insertNode(3); root->right = insertNode(7); root->left->left = insertNode(1); root->left->right = insertNode(5); root->right->left = insertNode(2); cout<<"The size of the given tree is "<<findSize(root); return 0; }
Output
The size of the given tree is 6
- Related Articles
- Write a C# program to calculate a factorial using recursion
- C++ program to Calculate Factorial of a Number Using Recursion
- C++ Program to Calculate Power Using Recursion
- Write a program to Delete a Tree in C programming
- How to calculate Power of a number using recursion in C#?
- Write a program to calculate pow(x,n) in C++
- Java program to calculate the power of a Given number using recursion
- Java program to calculate the GCD of a given number using recursion
- C++ Program for Inorder Tree Traversal without Recursion
- How to invert a binary search tree using recursion in C#?
- Write a Program to Find the Maximum Depth or Height of a Tree in C++
- C++ Program to Find Size of the Largest Independent Set(LIS) in a Given a Binary Tree
- How to check whether a binary tree is a valid binary search tree using recursion in C#?
- Print ancestors of a given binary tree node without recursion in C++
- Write a Golang program to find the factorial of a given number (Using Recursion)

Advertisements