Open In App

Write a program to Calculate Size of a tree | Recursion

Last Updated : 25 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Basic
82.91%
57.5K

Given a binary tree, the task is to find the size of the tree. The size of a tree is the number of nodes present in the tree.

Examples:

Input:

check-if-removing-an-edge-can-divide-a-binary-tree-in-two-halves

Output: 6
Explanation: The number of nodes in the above binary tree is 6.

Approach:

The idea is to recursively calculate the size of tree. For each node (starting from root node), calculate the size of left subtree and right subtree and return the size of current subtree (size of left subtree + size of right subtree + 1).

Below is the implementation of the above approach:

C++
// C++ program to find the size
// of a binary tree.
#include<bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node *left, *right;
    Node(int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// Recursive function to find the 
// size of binary tree.
int getSize(Node* root) {
    if (root == nullptr)
        return 0;
    
    // Find the size of left and right 
    // subtree.
    int left = getSize(root->left);
    int right = getSize(root->right);
    
    // return the size of curr subtree.
    return left+right+1;
}

int main() {

    // Constructed binary tree is
    //         1
    //        / \
    //       2   3
    //      / \
    //     4   5
    Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    cout << getSize(root) << endl;

    return 0;
}
C
// C program to find the size
// of a binary tree.
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

// Recursive function to find the 
// size of binary tree.
int getSize(struct Node* root) {
    if (root == NULL)
        return 0;
    
    // Find the size of left and right 
    // subtree.
    int left = getSize(root->left);
    int right = getSize(root->right);
    
    // return the size of curr subtree.
    return left + right + 1;
}

struct Node* createNode(int x) {
    struct Node* newNode = 
    (struct Node*)malloc(sizeof(struct Node));
    newNode->data = x;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

int main() {

    // Constructed binary tree is
    //         1
    //        / \
    //       2   3
    //      / \
    //     4   5
    struct Node* root = createNode(1);
    root->left = createNode(2);
    root->right = createNode(3);
    root->left->left = createNode(4);
    root->left->right = createNode(5);

    printf("%d\n", getSize(root));

    return 0;
}
Java
// Java program to find the size
// of a binary tree.
import java.util.*;

class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Recursive function to find the 
    // size of binary tree.
    static int getSize(Node root) {
        if (root == null)
            return 0;

        // Find the size of left and right 
        // subtree.
        int left = getSize(root.left);
        int right = getSize(root.right);

        // return the size of curr subtree.
        return left + right + 1;
    }

    public static void main(String[] args) {

        // Constructed binary tree is
        //         1
        //        / \
        //       2   3
        //      / \
        //     4   5
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);

        System.out.println(getSize(root));
    }
}
Python
# Python program to find the size
# of a binary tree.

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Recursive function to find the 
# size of binary tree.
def getSize(root):
    if root is None:
        return 0

    # Find the size of left and right 
    # subtree.
    left = getSize(root.left)
    right = getSize(root.right)

    # return the size of curr subtree.
    return left + right + 1

if __name__ == "__main__":

    # Constructed binary tree is
    #         1
    #        / \
    #       2   3
    #      / \
    #     4   5
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)

    print(getSize(root))
C#
// C# program to find the size
// of a binary tree.
using System;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Recursive function to find the 
    // size of binary tree.
    static int GetSize(Node root) {
        if (root == null)
            return 0;

        // Find the size of left and right 
        // subtree.
        int left = GetSize(root.left);
        int right = GetSize(root.right);

        // return the size of curr subtree.
        return left + right + 1;
    }

    static void Main(string[] args) {

        // Constructed binary tree is
        //         1
        //        / \
        //       2   3
        //      / \
        //     4   5
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);

        Console.WriteLine(GetSize(root));
    }
}
JavaScript
// JavaScript program to find the size
// of a binary tree.

class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Recursive function to find the 
// size of binary tree.
function getSize(root) {
    if (root === null)
        return 0;

    // Find the size of left and right 
    // subtree.
    let left = getSize(root.left);
    let right = getSize(root.right);

    // return the size of curr subtree.
    return left + right + 1;
}

// Constructed binary tree is
//         1
//        / \
//       2   3
//      / \
//     4   5
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);

console.log(getSize(root));

Output
5

Time Complexity: O(n), where n is the number of nodes in binary tree.
Auxiliary Space: O(h), where h is the height of the tree.



Previous Article
Next Article

Similar Reads

Iterative program to Calculate Size of a tree
Given a binary tree, the task is to find the size of the tree. The size of a tree is the number of nodes present in the tree. Example: Input: Output: 6Explanation: The number of nodes in the above binary tree is 6. Approach: The idea is to use Level Order Traversal to find the size of the tree. Initialize the count to 0. Push the root node into a q
5 min read
Program to calculate value of nCr using Recursion
Given two numbers N and r, find the value of NCr using recursion Examples: Input: N = 5, r = 2Output: 10Explanation: The value of 5C2 is 10 Input: N = 3, r = 1Output: 3 Approach 1: One very interesting way to find the C(n,r) is the recursive method which is based on the recursive equation. C(n,r) = C(n-1,r-1) + C(n-1,r) Below is the implementation
5 min read
Program to Calculate e^x by Recursion ( using Taylor Series )
The value of the Exponential function can be calculated using Taylor Series. [Tex]e^x[/Tex] = 1 + x/1! + [Tex]x^2[/Tex]/2! + [Tex]x^3[/Tex]/3! + ...... + until n termsAs the number of terms increases the more precise value of ex is obtained. To find e^x using the recursive function, we need to use static variables. A function can return only one va
5 min read
Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 min read
Write program to calculate pow(x, n)
Given two integers x and n, write a function to compute xn. We may assume that x and n are small and overflow doesn't happen. Examples :  Input : x = 2, n = 3Output : 8 Input : x = 7, n = 2Output : 49 Naive Approach: To solve the problem follow the below idea: A simple solution to calculate pow(x, n) would multiply x exactly n times. We can do that
15+ min read
Tail recursion to calculate sum of array elements.
Given an array A[], we need to find the sum of its elements using Tail Recursion Method. We generally want to achieve tail recursion (a recursive function where recursive call is the last thing that function does) so that compilers can optimize the code. Basically, if recursive call is the last statement, the compiler does not need to save the stat
3 min read
Write a program to Delete a Tree
To delete a tree, we must traverse all the nodes of the tree and delete them one by one. So, which traversal we should use - inorder traversal, preorder traversal, or the postorder traversal? The answer is simple. We should use the postorder traversal because before deleting the parent node, we should delete its child nodes first.We can delete the
11 min read
The Great Tree-List Recursion Problem.
Asked by Varun Bhatia. Question: Write a recursive function treeToList(Node root) that takes an ordered binary tree and rearranges the internal pointers to make a circular doubly linked list out of the tree nodes. The”previous” pointers should be stored in the “small” field and the “next” pointers should be stored in the “large” field. The list sho
1 min read
Print ancestors of a given binary tree node without recursion
Given a Binary Tree and a key, write a function that prints all the ancestors of the key in the given binary tree.For example, consider the following Binary Tree 1 / \ 2 3 / \ / \ 4 5 6 7 / \ / 8 9 10 Following are different input keys and their ancestors in the above tree Input Key List of Ancestors ------------------------- 1 2 1 3 1 4 2 1 5 2 1
15 min read
Postorder traversal of Binary Tree without recursion and without stack
Given a binary tree, perform postorder traversal. Prerequisite - Inorder/preorder/postorder traversal of tree We have discussed the below methods for postorder traversal. 1) Recursive Postorder Traversal. 2) Postorder traversal using Stack. 2) Postorder traversal using two Stacks. Approach 1 The approach used is based on using an unordered set to k
15 min read
Preorder Traversal of N-ary Tree Without Recursion
Given an n-ary tree, print preorder traversal of it. Example : Preorder traversal of below tree is A B K N M J F D G E C H I L The idea is to use stack like iterative preorder traversal of binary tree. Create an empty stack to store nodes. Push the root node to the stack. Run a loop while the stack is not empty Pop the top node from stack. Print th
7 min read
Find the node with maximum value in a Binary Search Tree using recursion
Given a Binary Search Tree, the task is to find the node with maximum value. Examples: Input: Output: 22 Approach: Just traverse the node from root to right recursively until right is NULL. The node whose right is NULL is the node with the maximum value. Below is the implementation of the above approach: C/C++ Code // C++ implementation of the appr
7 min read
Find maximum and minimum element in binary tree without using recursion or stack or queue
Given a binary tree. The task is to find out the maximum and minimum element in a binary tree without using recursion or stack or queue i.e, space complexity should be O(1). Examples: Input : 12 / \ 13 10 / \ 14 15 / \ / \ 21 24 22 23 Output : Max element : 24 Min element : 10 Input : 12 / \ 19 82 / / \ 41 15 95 \ / / \ 2 21 7 16 Output : Max eleme
10 min read
Find Maximum Level Sum in Binary Tree using Recursion
Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum level in it and print the maximum sum.Examples: Input: 4 / \ 2 -5 / \ / \ -1 3 -2 6 Output: 6 Sum of all nodes of the 1st level is 4. Sum of all nodes of the 2nd level is -3. Sum of all nodes of the 3rd level is 6. Hence, the maximum sum is 6. Input: 1 / \ 2
10 min read
Product of nodes at k-th level in a tree represented as string using Recursion
Prerequisite: Product of nodes at k-th level in a tree represented as stringGiven an integer ‘K’ and a binary tree in string format. Every node of a tree has value in range from 0 to 9. We need to find product of elements at K-th level from the root. The root is at level 0.Note: Tree is given in the form: (node value(left subtree)(right subtree))Ex
5 min read
Construct a Binary Tree in Level Order using Recursion
Given an array of integers, the task is to construct a binary tree in level order fashion using Recursion. Examples Given an array arr[] = {15, 10, 20, 8, 12, 16, 25} Approach: Idea is to keep track of the number of child nodes in the left sub-tree and right sub-tree and then take the decision on the basis of these counts. When the count of childre
10 min read
Pre Order, Post Order and In Order traversal of a Binary Tree in one traversal | (Using recursion)
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order in one iteration. Examples: Input: Output: Pre Order: 1 2 4 5 3 6 7 Post Order: 4 5 2 6 7 3 1 In Order: 4 2 5 1 6 3 7 Input: Output: Pre Order: 1 2 4 8 12 5 9 3 6 7 10 11 Post Order: 12 8 4 9 5 2 6 10 11 7 3 1 In Order: 8 12 4 2 9 5 1 6
9 min read
Inorder Tree Traversal without Recursion
In this post, we have seen in detail about the Inorder traversal and how it is implemented using recursion. Here in this post, we will discuss methods to implement inorder traversal without using recursion. Inorder Traversal using Stack:As we already know, recursion can also be implemented using stack. Here also we can use a stack to perform inorde
15+ min read
Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
We have discussed Thread based Morris Traversal. Can we do inorder traversal without threads if we have parent pointers available to us? Input: Root of Below Tree [Every node of tree has parent pointer also] 10 / \ 5 100 / \ 80 120 Output: 5 10 80 100 120 The code should not extra space (No Recursion and stack) In inorder traversal, we follow "left
11 min read
How to solve time complexity Recurrence Relations using Recursion Tree method?
The Recursion Tree Method is a way of solving recurrence relations. In this method, a recurrence relation is converted into recursive trees. Each node represents the cost incurred at various levels of recursion. To find the total cost, costs of all levels are summed up. Steps to solve recurrence relation using recursion tree method: Draw a recursiv
4 min read
Find the node with minimum value in a Binary Search Tree using recursion
Given the root of a Binary Search Tree, the task is to find the minimum valued element in this given BST. Examples: Input: Output: 1Explanation: The minimum element in the given BST is 1. Input: Output: 2Explanation: The minimum element in the given BST is 2. Approach: The idea is to recursively traverse the Binary Search Tree (BST) starting from t
6 min read
Print Root-to-Leaf Paths in a Binary Tree Using Recursion
Given a Binary Tree of nodes, the task is to find all the possible paths from the root node to all the leaf nodes of the binary tree. Example: Input: Output: 1 2 41 2 51 3 Approach: The approach involves using recursion to traverse a Binary tree. The recursive function will append node values to a path as it navigates down the tree. After reaching
6 min read
Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
Given Preorder traversal of a Binary Search Tree. Then the task is to print leaf nodes of the Binary Search Tree from the given preorder. Examples : Input : preorder[] = {890, 325, 290, 530, 965};Output : 290 530 965Explanation: Below is the representation of BST using preorder array. Approach: To identify leaf nodes from a given preorder traversal
8 min read
Inorder Tree Traversal without recursion and without stack!
Given a Binary Tree, the task is to print its Inorder Traversal, without using recursion or stack. Examples: Input: Output: 4 2 5 1 3Explanation: Inorder traversal (Left->Root->Right) of the tree is 4 2 5 1 3 Input: Output: 1 7 10 8 6 10 5 6Explanation: Inorder traversal (Left->Root->Right) of the tree is 1 7 10 8 6 10 5 6 Approach: Usi
9 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Convert a Generic Tree(N-array Tree) to Binary Tree
Prerequisite: Generic Trees(N-array Trees) In this article, we will discuss the conversion of the Generic Tree to a Binary Tree. Following are the rules to convert a Generic(N-array Tree) to a Binary Tree: The root of the Binary Tree is the Root of the Generic Tree.The left child of a node in the Generic Tree is the Left child of that node in the B
13 min read
Program for length of a string using recursion
Given a string calculate length of the string using recursion. Examples: Input : str = "abcd" Output :4 Input : str = "GEEKSFORGEEKS" Output :13 We have discussed 5 Different methods to find length of a string in C++ How to find length of a string without string.h and loop in C? Algorithm: recLen(str) { If str is NULL return 0 Else return 1 + recLe
3 min read
Program to check if an array is palindrome or not using Recursion
Given an array. The task is to determine whether an array is a palindrome or not using recursion. Examples: Input: arr[] = {3, 6, 0, 6, 3}Output: Palindrome Input: arr[] = {1, 2, 3, 4, 5}Output: Not Palindrome Approach: Base case: If array has only one element i.e. begin == end then return 1, also if begin>end which means the array is palindrome
4 min read
Program to find all Factors of a Number using recursion
Given a number N, the task is to print all the factors of N using recursion.Examples: Input: N = 16 Output: 1 2 4 8 16 Explanation: 1, 2, 4, 8, 16 are the factors of 16. A factor is a number which divides the number completely. Input: N = 8 Output: 1 2 4 8 Approach: The idea is to create a function that takes 2 arguments. The function is recursivel
3 min read
C Program to find LCM of two numbers using Recursion
Given two integers N and M, the task is to find their LCM using recursion. Examples: Input: N = 2, M = 4Output: 4Explanation: LCM of 2, 4 is 4. Input: N = 3, M = 5Output: 15Explanation: LCM of 3, 5 is 15. Approach: The idea is to use the basic elementary method of finding LCM of two numbers. Follow the steps below to solve the problem: Define a rec
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg