Iterative program to Calculate Size of a tree | C ++ program to print size of tree in iterative ; Node Structure ; A utility function to create a new Binary Tree Node ; return size of tree ; if tree is empty it will return 0 ; Using level order Traversal . ; when the queue is empty : the poll ( ) method returns null . ; Increment count ; Enqueue left child ; Increment count ; Enqueue right child ; Driver Code ; creating a binary tree and entering the nodes
#include <iostream> NEW_LINE #include <queue> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = NULL ; temp -> right = NULL ; return temp ; } int sizeoftree ( Node * root ) { if ( root == NULL ) return 0 ; queue < Node * > q ; int count = 1 ; q . push ( root ) ; while ( ! q . empty ( ) ) { Node * temp = q . front ( ) ; if ( temp -> left ) { count ++ ; q . push ( temp -> left ) ; } if ( temp -> right ) { count ++ ; q . push ( temp -> right ) ; } q . pop ( ) ; } return count ; } int 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 ; }