Iterative 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 ; 1 / \ 2 3 / \ 4 5 Let us create Binary Tree shown in above example ; get leaf count of the above created tree
class Node { constructor ( data ) { this . data = data ; this . left = this . right = null ; } } function getLeafCount ( node ) { if ( node == null ) { return 0 ; } let q = [ ] ; let count = 0 ; q . push ( node ) ; while ( q . length != 0 ) { let temp = q . shift ( ) ; if ( temp . left != null ) { q . push ( temp . left ) ; } if ( temp . right != null ) { q . push ( temp . right ) ; } if ( temp . left == null && temp . right == null ) { count ++ ; } } return count ; } let root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 3 ) ; root . left . left = new Node ( 4 ) ; root . left . right = new Node ( 5 ) ; document . write ( getLeafCount ( root ) ) ;