Open In App

Iterative program to Calculate Size of a tree

Last Updated : 26 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

size

Output: 6
Explanation: 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 queue. While queue is not empty, for each node, increment the count. Push its left (if exists) and right (if exists) into the queue. Return the count.

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;
    }
};

// Iterative function to find the 
// size of binary tree.
int getSize(Node* root) {
    if (root == nullptr)
        return 0;
    
    int cnt = 0;
    queue<Node*> q;
    q.push(root);
    
    while (!q.empty()) {
        Node* curr = q.front();
        q.pop();
        
        // increment the count
        cnt++;
        
        if (curr->left!=nullptr)
            q.push(curr->left);
        if (curr->right!=nullptr)
            q.push(curr->right);
    }
    
    return cnt;
}

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;
}
Java
// Java program to find the size
// of a binary tree.

import java.util.Queue;
import java.util.LinkedList;

class Node {
    int data;
    Node left, right;

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

class GfG {

    // Iterative function to find the 
    // size of binary tree.
    static int getSize(Node root) {
        if (root == null)
            return 0;
        
        int cnt = 0;
        Queue<Node> q = new LinkedList<>();
        q.add(root);
        
        while (!q.isEmpty()) {
            Node curr = q.poll();
            
            // increment the count
            cnt++;
            
            if (curr.left != null)
                q.add(curr.left);
            if (curr.right != null)
                q.add(curr.right);
        }
        
        return cnt;
    }

    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.
from collections import deque

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

# Iterative function to find the 
# size of binary tree.
def getSize(root):
    if root is None:
        return 0
    
    cnt = 0
    q = deque([root])
    
    while q:
        curr = q.popleft()
        
        # increment the count
        cnt += 1
        
        if curr.left is not None:
            q.append(curr.left)
        if curr.right is not None:
            q.append(curr.right)
    
    return cnt

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;
using System.Collections.Generic;

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

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

class GfG {

    // Iterative function to find the 
    // size of binary tree.
    static int getSize(Node root) {
        if (root == null)
            return 0;
        
        int cnt = 0;
        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);
        
        while (q.Count > 0) {
            Node curr = q.Dequeue();
            
            // increment the count
            cnt++;
            
            if (curr.left != null)
                q.Enqueue(curr.left);
            if (curr.right != null)
                q.Enqueue(curr.right);
        }
        
        return cnt;
    }

    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;
    }
}

// Iterative function to find the 
// size of binary tree.
function getSize(root) {
    if (root === null)
        return 0;
    
    let cnt = 0;
    let q = [];
    q.push(root);
    
    while (q.length > 0) {
        let curr = q.shift();
        
        // increment the count
        cnt++;
        
        if (curr.left !== null)
            q.push(curr.left);
        if (curr.right !== null)
            q.push(curr.right);
    }
    
    return cnt;
}

// 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 the tree. 
Auxiliary Space: O(n).

Related Article:


Next Article
Article Tags :
Practice Tags :

Similar Reads