Iterative program to count leaf nodes in a Binary Tree | Java 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
import java . util . * ; class GFG { static class Node { int data ; Node left , right ; } static int getLeafCount ( Node node ) { if ( node == null ) { return 0 ; } Queue < Node > q = new LinkedList < > ( ) ; int count = 0 ; q . add ( node ) ; while ( ! q . isEmpty ( ) ) { Node temp = q . peek ( ) ; q . poll ( ) ; if ( temp . left != null ) { q . add ( temp . left ) ; } if ( temp . right != null ) { q . add ( 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 ) ; System . out . println ( getLeafCount ( root ) ) ; } } }