Iterative program to Calculate Size of a tree - GeeksforGeeks

30 Jun, 2021
Size of a tree is the number of elements present in the tree. Size of the below tree is 5.  
 
Approach The idea is to use Level Order Traversing  
1) Create an empty queue q
2) temp_node = root /*start from root*/
3) Loop while temp_node is not NULL
    a) Enqueue temp_node’s children (first left then right children) to q
    b) Increase count with every enqueuing.
    c) Dequeue a node from q and assign it’s value to temp_node
 
C++
Java
Python3
C#
Javascript
// C++ program to print size of tree in iterative#include<iostream>#include<queue>using namespace std; struct Node{    int data;    Node *left, *right;}; // A utility function to// create a new Binary Tree NodeNode *newNode(int data){    Node *temp = new Node;    temp->data = data;    temp->left = NULL;    temp->right = NULL;         return temp;} // return size of treeint sizeoftree(Node *root){     // if tree is empty it will    // return 0    if(root == NULL)        return 0;              // Using level order Traversal.    queue<Node *> q;    int count = 1;    q.push(root);         while(!q.empty())    {        Node *temp = q.front();             if(temp->left)        {            // Enqueue left child            q.push(temp->left);                         // Increment count            count++;        }             if(temp->right)        {            // Enqueue right child            q.push(temp->right);                         // Increment count            count++;        }        q.pop();    }         return count;} // Driver Codeint main(){    Node *root = newNode(1);    root->left = newNode(2);    root->right = newNode(3);    root->left->left = newNode(4);    root->left->right = newNode(5);     cout << "Size of the tree is " <<        sizeoftree(root) << endl;    return 0;} // This code is contributed by SHAKEELMOHAMMAD
// Java programn to calculate// Size of a treeimport java.util.LinkedList;import java.util.Queue; class Node{    int data;    Node left, right;     public Node(int item)    {        data = item;        left = right = null;    }} class BinaryTree{    Node root;             public int size()    {        if (root == null)            return 0;                 // Using level order Traversal.        Queue<Node> q = new LinkedList<Node>();        q.offer(root);                 int count = 1;        while (!q.isEmpty())        {            Node tmp = q.poll();                 // when the queue is empty:            // the poll() method returns null.            if (tmp != null)            {                if (tmp.left != null)                {                    // Increment count                    count++;                                         // Enqueue left child                    q.offer(tmp.left);                }                if (tmp.right != null)                {                    // Increment count                    count++;                                         // Enqueue left child                    q.offer(tmp.right);                }            }        }                 return count;    }     public static void main(String args[])    {        /* creating a binary tree and entering          the nodes */        BinaryTree tree = new BinaryTree();        tree.root = new Node(1);        tree.root.left = new Node(2);        tree.root.right = new Node(3);        tree.root.left.left = new Node(4);        tree.root.left.right = new Node(5);         System.out.println("The size of binary tree" +                         " is : " + tree.size());    }}
# Python Program to calculate size of the tree iteratively # Node Structureclass newNode:    def __init__(self,data):        self.data = data        self.left = self.right = None         # Return size of treedef sizeoftree(root):    if root == None:        return 0    q = []    q.append(root)    count = 1    while(len(q) != 0):        root = q.pop(0)        if(root.left):            q.append(root.left)            count += 1        if(root.right):            q.append(root.right)            count += 1    return count     # Driver Programroot = newNode(1)root.left = newNode(2)root.right = newNode(3)root.left.left = newNode(4)root.left.right = newNode(5)print(sizeoftree(root)) # This is code is contributed by simranjenny84
// C# programn to calculate// Size of a treeusing System;using System.Collections.Generic; public class Node{    public int data;    public Node left, right;     public Node(int item)    {        data = item;        left = right = null;    }} public class BinaryTree{    Node root;             public int size()    {        if (root == null)            return 0;                 // Using level order Traversal.        Queue<Node> q = new Queue<Node>();        q.Enqueue(root);                 int count = 1;        while (q.Count != 0)        {            Node tmp = q.Dequeue();                 // when the queue is empty:            // the poll() method returns null.            if (tmp != null)            {                if (tmp.left != null)                {                    // Increment count                    count++;                                         // Enqueue left child                    q.Enqueue(tmp.left);                }                if (tmp.right != null)                {                    // Increment count                    count++;                                         // Enqueue left child                    q.Enqueue(tmp.right);                }            }        }                 return count;    }     // Driver code    public static void Main(String []args)    {        /* creating a binary tree and entering        the nodes */        BinaryTree tree = new BinaryTree();        tree.root = new Node(1);        tree.root.left = new Node(2);        tree.root.right = new Node(3);        tree.root.left.left = new Node(4);        tree.root.left.right = new Node(5);         Console.WriteLine("The size of binary tree" +                        " is : " + tree.size());    }} // This code has been contributed by 29AjayKumar
<script>     // JavaScript programn to calculate Size of a tree         class Node    {        constructor(item) {           this.left = null;           this.right = null;           this.data = item;        }    }         let root;               function size()    {        if (root == null)            return 0;                   // Using level order Traversal.        let q = [];        q.push(root);                   let count = 1;        while (q.length > 0)        {            let tmp = q[0];            q.shift();                   // when the queue is empty:            // the poll() method returns null.            if (tmp != null)            {                if (tmp.left != null)                {                    // Increment count                    count++;                                           // Enqueue left child                    q.push(tmp.left);                }                if (tmp.right != null)                {                    // Increment count                    count++;                                           // Enqueue left child                    q.push(tmp.right);                }            }        }                   return count;    }         /* creating a binary tree and entering            the nodes */    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);     document.write("Size of the tree is " + size());     </script>
Output:  
Size of the tree is 5
Time Complexity: O(n) Auxiliary Space: O(level_max) where level max is maximum number of node in any level.  
YouTubeGeeksforGeeks507K subscribersIterative program to Calculate Size of a tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:37•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=0gPDf0n4A2M" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
29AjayKumar
SHAKEELMOHAMMAD
simranjenny84
decode2207
java-LinkedList
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Tree Data Structure
DFS traversal of a tree using recursion
Top 50 Tree Coding Problems for Interviews
Find the node with minimum value in a Binary Search Tree
Print Binary Tree in 2-Dimensions
Real-time application of Data Structures
Iterative Postorder Traversal | Set 2 (Using One Stack)
Find maximum (or minimum) in Binary Tree
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Difference between Min Heap and Max Heap