Iterative program to Calculate Size of a tree | C # 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
using 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 ; Queue < Node > q = new Queue < Node > ( ) ; q . Enqueue ( root ) ; int count = 1 ; while ( q . Count != 0 ) { Node tmp = q . Dequeue ( ) ; if ( tmp != null ) { if ( tmp . left != null ) { count ++ ; q . Enqueue ( tmp . left ) ; } if ( tmp . right != null ) { count ++ ; q . Enqueue ( 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 ) ; Console . WriteLine ( " The ▁ size ▁ of ▁ binary ▁ tree " + " ▁ is ▁ : ▁ " + tree . size ( ) ) ; } }