Iterative program to count leaf nodes in a Binary Tree | 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
class Node { constructor ( data ) { this . data = data ; this . next = this . right = null ; } } function countLeaves ( node ) { if ( node == null ) return 0 ; if ( node . left == null && node . right == null ) return 1 ; return countLeaves ( node . left ) + countLeaves ( node . right ) ; } 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 ( countLeaves ( root ) ) ;