Iterative program to count leaf nodes in a Binary Tree | C # 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 ; Driver Code ; Get leaf count of the above created tree
using System ; public class Node { public int data ; public Node left , right ; public Node ( int d ) { data = d ; left = right = null ; } } public class BinaryTree { public static Node root ; 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 public void Main ( ) { BinaryTree . root = new Node ( 1 ) ; BinaryTree . root . left = new Node ( 2 ) ; BinaryTree . root . right = new Node ( 3 ) ; BinaryTree . root . left . left = new Node ( 4 ) ; BinaryTree . root . left . right = new Node ( 5 ) ; Console . WriteLine ( countLeaves ( root ) ) ; } }