Iterative program to count leaf nodes in a Binary Tree | C # program to count leaf nodes in a Binary Tree ; A binary tree Node has data , pointer to left child and a pointer to right child ; Function to get the count of leaf Nodes in a binary tree ; If tree is empty ; Initialize empty queue . ; Do level order traversal starting from root Initialize count of leaves ; Helper function that allocates a new Node with the given data and null left and right pointers . ; Driver Code ; 1 / \ 2 3 / \ 4 5 Let us create Binary Tree shown in above example ; get leaf count of the above created tree
using System ; using System . Collections . Generic ; class GFG { public class Node { public int data ; public Node left , right ; } static int getLeafCount ( Node node ) { if ( node == null ) { return 0 ; } Queue < Node > q = new Queue < Node > ( ) ; int count = 0 ; q . Enqueue ( node ) ; while ( q . Count != 0 ) { Node temp = q . Peek ( ) ; q . Dequeue ( ) ; if ( temp . left != null ) { q . Enqueue ( temp . left ) ; } if ( temp . right != null ) { q . Enqueue ( temp . right ) ; } if ( temp . left == null && temp . right == null ) { count ++ ; } } return count ; } static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . left = node . right = null ; return ( node ) ; } public static void Main ( String [ ] args ) { { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 5 ) ; Console . WriteLine ( getLeafCount ( root ) ) ; } } }