Iterative program to count leaf nodes in a Binary Tree | Java Program for above approach ; Node class ; Program to count leaves ; If the node itself is " null " return 0 , as there are no leaves ; It the node is a leaf then both right and left children will be " null " ; Now we count the leaves in the left and right subtrees and return the sum ; Class newNode of Node type ; Driver Code ; get leaf count of the above created tree
import java . util . LinkedList ; import java . util . Queue ; import java . io . * ; import java . util . * ; class GfG { static class Node { int data ; Node left , right ; } static int countLeaves ( Node node ) { if ( node == null ) return 0 ; if ( node . left == null && node . right == null ) return 1 ; return countLeaves ( node . left ) + countLeaves ( node . right ) ; } 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 ( countLeaves ( root ) ) ; } }