Iterative program to Calculate Size of a tree | Java programn to calculate Size of a tree ; Node Structure ; 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
import 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 ; Queue < Node > q = new LinkedList < Node > ( ) ; q . offer ( root ) ; int count = 1 ; while ( ! q . isEmpty ( ) ) { Node tmp = q . poll ( ) ; if ( tmp != null ) { if ( tmp . left != null ) { count ++ ; q . offer ( tmp . left ) ; } if ( tmp . right != null ) { count ++ ; q . offer ( tmp . right ) ; } } } return count ; } public static void main ( String args [ ] ) { 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 ( ) ) ; } }